Пытаясь делать курсовую работу, застрял вот на таком моменте:
Вот скриншот консоли на каком месте остановилась программа:
Я делаю решение системы линейных уравнений и думаю, что ошибка кроется в cout и cin, а именно в буфере ввода. Как я понял из информации в интернете, это происходит из-за того, что в нём остаётся символ \n
и от этого все проблема, но это не точно.
Когда убираешь <<z<<
и остаётся просто: "Введите коэффициенты неизвестных уравнения через ;" << endl;
— то программа продолжает работать и после ввода
коэффициентов, и вывода следующего cout опять та же ошибка. Уже пробовал всякие
cin.sync()
и cin.clear()
, но ничего не изменилось. Помогите пожалуйста и объясните как исправить.
#include <cuda.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include<locale.h>
#include<curand.h>
#include<curand_kernel.h>
#include<time.h>
#include <stdlib.h>
#include <string>
#include <cstdio>
using namespace std;
__global__ void vichislenie( int *index, float *mas, int *kolvoperem )
{
int indexGPU = threadIdx.x + *kolvoperem - 1 ;
//for
//while (index < 33792)
//{
/*if (*number < mas1[index])
*otvchislo = 0;*/
//index += blockDim.x * gridDim.x;
//}
}
/*float *randomer(float *mas)
{
for (unsigned short i = 0; i < 33792; i++)
mas[i] = 0.01 * (rand() % 10100);
return mas;
}*/
int main( void )
{
setlocale( LC_ALL, "RUS" );
unsigned short kolvostrok = 0;
int kolvoperem = 0;
int index = 0;
float *masOtvet = new float[kolvostrok];
cout << "Введите кол-во неизвестных переменных: ";
cin >> kolvostrok;
cout << "Введите кол-во уравнений: ";
cin >> kolvoperem;
cout << "Введите правые части уравнений: ";
for( unsigned short i = 0; i < kolvostrok; i++ ) {
cin >> masOtvet[i];
cin.sync();
/*cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
cin.get();*/
//int dummy; my_cin(dummy);
}
index = kolvostrok * kolvoperem;
float *masKoefic = new float[index];
for( unsigned short i = 0; i < index ; i++ ) {
masKoefic[i] = 0.0;
}
char *str = new char[kolvoperem * 2 * kolvostrok * 16];
for( unsigned short i = 0; i < ( strlen( str ) ); i++ ) {
str[i] = ' ';
}
unsigned short schetchik = 1;
unsigned short schetchik1 = 0;
char *StrBufMas = new char[kolvoperem * 2 * 16];
for( int z = 1; z < kolvostrok + 1; z++ ) {
/*cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
cin.get();*/
cout << "Введите коэфициенты неизвестных уравнения "
<< z << " через ;" << endl;
cout << "(если в уравнении не полное кол-во переменных, то вместо них поставить нули): "
<< endl;
cin >> StrBufMas;
}
//scanf("%s", *StrBufMas);
schetchik1 = 1;
for( unsigned short i = 0; i < kolvoperem * 2 * kolvostrok * 16; i++ ) {
if( ( str[i + 1] ) == ' ' ) {
if( schetchik1 == 1 ) {
}
else {
break;
}
for( unsigned short i = 0; i < strlen( StrBufMas ); i++ ) {
str[i + schetchik] = StrBufMas[i];
if( i == ( strlen( StrBufMas ) ) - 1 ) {
schetchik = schetchik + strlen( StrBufMas ) + 1;
schetchik1 = 0;
}
}
}
}
/*size_t t = 6;
char s1[10] = " tttrrrrr";
char *s2 = new char[1];
strcpy(s2, (s1-t));*/
delete [kolvoperem * 2 * 16] StrBufMas, StrBufMas = NULL;
schetchik = 0;
schetchik1 = 0;
char StrBufMas1[16] = "";
for( unsigned short i = 0; i < strlen( str ) - 1; i++ ) {
if( ( str[i] == ' ' ) || ( str[i] == ';' ) ) {
//i -= 1;
}
else {
schetchik++;
schetchik1++;
/*char *StrBufMas = new char[schetchik1];
StrBufMas[schetchik1 - 1] = str[i];*/
//strcat(StrBufMas1, &str[i]);
if( ( str[i + 1] == ' ' ) || ( str[i + 1] == ';' ) ) {
strncpy( StrBufMas1, &str[i - schetchik1 + 1], schetchik1 );
masKoefic[i - schetchik] = atof( StrBufMas1 );
//StrBufMas1 = ;
//delete[schetchik1] StrBufMas;
schetchik1 = 0;
for( unsigned char j = 15; j > 0; j-- ) {
StrBufMas1[j] = '\0';
}
}
}
}
float *masAll = new float[index - 1 + kolvostrok];
schetchik = 0;
schetchik1 = 1;
for( unsigned short i = 0; i < index - 1 + kolvostrok; i++ ) {
if( i == ( index + schetchik ) / kolvostrok ) {
masAll[i] = masOtvet[i - ( i * schetchik1 )];
schetchik1++;
schetchik = schetchik + index + kolvostrok;
}
else {
masAll[i] = masKoefic[i];
}
}
float *dev_mas;
int *dev_index;
int *dev_kolvoperem;
cudaMalloc( ( void ** )&dev_index, sizeof( int ) );
cudaMalloc( ( void ** )&dev_mas, sizeof( float ) );
cudaMalloc( ( void ** )&dev_kolvoperem, sizeof( int ) );
cudaMemcpy( dev_index, &index, sizeof( int ), cudaMemcpyHostToDevice );
cudaMemcpy( dev_mas, &masKoefic, index * sizeof( float ),
cudaMemcpyHostToDevice );
cudaMemcpy( dev_kolvoperem, &kolvoperem, sizeof( int ),
cudaMemcpyHostToDevice );
vichislenie << <1, kolvoperem >> > ( dev_index, dev_mas, dev_kolvoperem );
//n = atoi(S.c_str())
/*float number;
cout << "Введите число k: ";
cin >> number;
int otvchislo = 1;
int *dev_otvchislo;
float *dev_number;
unsigned short i = 256;
while (i != 0)
{
cudaMalloc((void**)&dev_otvchislo, sizeof(int));
cudaMalloc((void**)&dev_number, sizeof(float));
cudaMemcpy(dev_otvchislo, &otvchislo, sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(dev_number, &number, sizeof(float), cudaMemcpyHostToDevice);
float mas[33792];
float *dev_mas1;
randomer(mas);
cudaMalloc((void**)&dev_mas1, 33792 * sizeof(float));
cudaMemcpy(dev_mas1, &mas, 33792 * sizeof(float), cudaMemcpyHostToDevice);
vichislenie << <128, 128 >> > (dev_number, dev_otvchislo, dev_mas1);
cudaMemcpy(&mas, dev_mas1, 33792 * sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(&otvchislo, dev_otvchislo, sizeof(int), cudaMemcpyDeviceToHost);
cudaFree(dev_mas1);
cudaFree(dev_number);
cudaFree(dev_otvchislo);
i -= 1;
}
if (otvchislo == 1)
{
unsigned char otv[4] = "да";
cout << "Число k больше всех чисел в матрице? -" << otv << "\n";
}
else
{
unsigned char otv[4] = "нет";
cout << "Число k больше всех чисел в матрице? -" << otv << "\n";
}*/
system( "pause" );
return 0;
}
Zylaks 0 / 0 / 1 Регистрация: 12.04.2015 Сообщений: 47 |
||||
1 |
||||
Ошибка при чтении символов строки09.08.2015, 12:12. Показов 2299. Ответов 5 Метки нет (Все метки)
Как я понял, что ошибка из-за функции ChooseAnswer. При использовании return. Если в каждый Case прописать Return Answer, то ошибок нет, а если написать один раз в конце функции, то выводит ошибку: Answer — Ошибка при чтении символов строки. В чем ошибка?
0 |
528 / 431 / 159 Регистрация: 25.11.2014 Сообщений: 1,662 |
|
09.08.2015, 12:17 |
2 |
Поставь return Answer за switch. Потому что сейчас он относится к default.
0 |
0 / 0 / 1 Регистрация: 12.04.2015 Сообщений: 47 |
|
09.08.2015, 12:25 [ТС] |
3 |
Если я поставлю за switch, то функция завершится, не дойдя до switch. Понял ошибку, надо за скобку вынести, я не заметил, как return В switch запихнул.
0 |
Заблокирован |
||||
09.08.2015, 12:29 |
4 |
|||
0 |
528 / 431 / 159 Регистрация: 25.11.2014 Сообщений: 1,662 |
|
09.08.2015, 12:33 |
5 |
Если я поставлю за switch, то функция завершится, не дойдя до switch. C чего бы? Return будет вызываться после отработки switch.
Понял ошибку, надо за скобку вынести Я это и написал.
0 |
4 / 4 / 2 Регистрация: 22.04.2015 Сообщений: 58 |
|
09.08.2015, 14:32 |
6 |
В свитче так же можно использовать return Answer; вместо break; тогда программе не потребуется идти до конца функции, чтобы вернуть результат.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
09.08.2015, 14:32 |
6 |
I have the following block of code:
for( CarsPool::CarRecord &record : recs->GetRecords())
{
LVITEM item;
item.mask = LVIF_TEXT;
item.cchTextMax = 6;
item.iSubItem = 0;
item.pszText = (LPSTR)(record.getCarName().c_str()); //breakpoint on this line.
item.iItem = 0;
ListView_InsertItem(CarsListView, &item);
item.iSubItem = 1;
item.pszText = TEXT("Available");
ListView_SetItem(CarsListView, &item);
item.iSubItem = 2;
item.pszText = (LPSTR)CarsPool::EncodeCarType(record.getCarType());
ListView_SetItem(CarsListView, &item);
}
The information from Visual Studio Debugger is here:
Why isn’t the program able to read the characters from string?
A test has shown me that it works in this way:
MessageBox(hWnd, (LPSTR)(record.getCarName().c_str()), "Test", MB_OK);
asked Sep 22, 2013 at 17:07
3
getCarName
likely returns a temporary. After the assignment the temporary object is destroyed and the pointer item.pszText
points to invalid memory. You must ensure that the string object is valid during the call to ListView_InsertItem
.
std::string text(record.getCarName());
item.iSubItem = 0;
item.pszText = const_cast<LPSTR>(text.c_str());
item.iItem = 0;
ListView_InsertItem(CarsListView, &item);
The const_cast
is an artifact of the fact that the Windows API uses the same structure to set and retrieve information. When invoking ListView_InsertItem
the structure is immutable, however there is no way to reflect that in the language.
answered Sep 22, 2013 at 17:26
IInspectableIInspectable
47.3k8 gold badges86 silver badges182 bronze badges
1
It looks like you’re trying to use the value of a C++ «string» in a C/Win32 call.
stdstring.c_str() is the correct way to do it.
… BUT …
You should strcpy() the string to a temp variable, then make the Win32 call with the temp variable.
answered Sep 22, 2013 at 17:18
paulsm4paulsm4
114k18 gold badges138 silver badges190 bronze badges
1
Пытаясь делать курсовую работу, застрял вот на таком моменте:
Вот скриншот консоли на каком месте остановилась программа:
Я делаю решение системы линейных уравнений и думаю, что ошибка кроется в cout и cin, а именно в буфере ввода. Как я понял из информации в интернете, это происходит из-за того, что в нём остаётся символ n
и от этого все проблема, но это не точно.
Когда убираешь <<z<<
и остаётся просто: "Введите коэффициенты неизвестных уравнения через ;" << endl;
— то программа продолжает работать и после ввода
коэффициентов, и вывода следующего cout опять та же ошибка. Уже пробовал всякие
cin.sync()
и cin.clear()
, но ничего не изменилось. Помогите пожалуйста и объясните как исправить.
#include <cuda.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include<locale.h>
#include<curand.h>
#include<curand_kernel.h>
#include<time.h>
#include <stdlib.h>
#include <string>
#include <cstdio>
using namespace std;
__global__ void vichislenie( int *index, float *mas, int *kolvoperem )
{
int indexGPU = threadIdx.x + *kolvoperem - 1 ;
//for
//while (index < 33792)
//{
/*if (*number < mas1[index])
*otvchislo = 0;*/
//index += blockDim.x * gridDim.x;
//}
}
/*float *randomer(float *mas)
{
for (unsigned short i = 0; i < 33792; i++)
mas[i] = 0.01 * (rand() % 10100);
return mas;
}*/
int main( void )
{
setlocale( LC_ALL, "RUS" );
unsigned short kolvostrok = 0;
int kolvoperem = 0;
int index = 0;
float *masOtvet = new float[kolvostrok];
cout << "Введите кол-во неизвестных переменных: ";
cin >> kolvostrok;
cout << "Введите кол-во уравнений: ";
cin >> kolvoperem;
cout << "Введите правые части уравнений: ";
for( unsigned short i = 0; i < kolvostrok; i++ ) {
cin >> masOtvet[i];
cin.sync();
/*cin.ignore(numeric_limits<streamsize>::max(), 'n');
cin.clear();
cin.get();*/
//int dummy; my_cin(dummy);
}
index = kolvostrok * kolvoperem;
float *masKoefic = new float[index];
for( unsigned short i = 0; i < index ; i++ ) {
masKoefic[i] = 0.0;
}
char *str = new char[kolvoperem * 2 * kolvostrok * 16];
for( unsigned short i = 0; i < ( strlen( str ) ); i++ ) {
str[i] = ' ';
}
unsigned short schetchik = 1;
unsigned short schetchik1 = 0;
char *StrBufMas = new char[kolvoperem * 2 * 16];
for( int z = 1; z < kolvostrok + 1; z++ ) {
/*cin.ignore(numeric_limits<streamsize>::max(), 'n');
cin.clear();
cin.get();*/
cout << "Введите коэфициенты неизвестных уравнения "
<< z << " через ;" << endl;
cout << "(если в уравнении не полное кол-во переменных, то вместо них поставить нули): "
<< endl;
cin >> StrBufMas;
}
//scanf("%s", *StrBufMas);
schetchik1 = 1;
for( unsigned short i = 0; i < kolvoperem * 2 * kolvostrok * 16; i++ ) {
if( ( str[i + 1] ) == ' ' ) {
if( schetchik1 == 1 ) {
}
else {
break;
}
for( unsigned short i = 0; i < strlen( StrBufMas ); i++ ) {
str[i + schetchik] = StrBufMas[i];
if( i == ( strlen( StrBufMas ) ) - 1 ) {
schetchik = schetchik + strlen( StrBufMas ) + 1;
schetchik1 = 0;
}
}
}
}
/*size_t t = 6;
char s1[10] = " tttrrrrr";
char *s2 = new char[1];
strcpy(s2, (s1-t));*/
delete [kolvoperem * 2 * 16] StrBufMas, StrBufMas = NULL;
schetchik = 0;
schetchik1 = 0;
char StrBufMas1[16] = "";
for( unsigned short i = 0; i < strlen( str ) - 1; i++ ) {
if( ( str[i] == ' ' ) || ( str[i] == ';' ) ) {
//i -= 1;
}
else {
schetchik++;
schetchik1++;
/*char *StrBufMas = new char[schetchik1];
StrBufMas[schetchik1 - 1] = str[i];*/
//strcat(StrBufMas1, &str[i]);
if( ( str[i + 1] == ' ' ) || ( str[i + 1] == ';' ) ) {
strncpy( StrBufMas1, &str[i - schetchik1 + 1], schetchik1 );
masKoefic[i - schetchik] = atof( StrBufMas1 );
//StrBufMas1 = ;
//delete[schetchik1] StrBufMas;
schetchik1 = 0;
for( unsigned char j = 15; j > 0; j-- ) {
StrBufMas1[j] = '';
}
}
}
}
float *masAll = new float[index - 1 + kolvostrok];
schetchik = 0;
schetchik1 = 1;
for( unsigned short i = 0; i < index - 1 + kolvostrok; i++ ) {
if( i == ( index + schetchik ) / kolvostrok ) {
masAll[i] = masOtvet[i - ( i * schetchik1 )];
schetchik1++;
schetchik = schetchik + index + kolvostrok;
}
else {
masAll[i] = masKoefic[i];
}
}
float *dev_mas;
int *dev_index;
int *dev_kolvoperem;
cudaMalloc( ( void ** )&dev_index, sizeof( int ) );
cudaMalloc( ( void ** )&dev_mas, sizeof( float ) );
cudaMalloc( ( void ** )&dev_kolvoperem, sizeof( int ) );
cudaMemcpy( dev_index, &index, sizeof( int ), cudaMemcpyHostToDevice );
cudaMemcpy( dev_mas, &masKoefic, index * sizeof( float ),
cudaMemcpyHostToDevice );
cudaMemcpy( dev_kolvoperem, &kolvoperem, sizeof( int ),
cudaMemcpyHostToDevice );
vichislenie << <1, kolvoperem >> > ( dev_index, dev_mas, dev_kolvoperem );
//n = atoi(S.c_str())
/*float number;
cout << "Введите число k: ";
cin >> number;
int otvchislo = 1;
int *dev_otvchislo;
float *dev_number;
unsigned short i = 256;
while (i != 0)
{
cudaMalloc((void**)&dev_otvchislo, sizeof(int));
cudaMalloc((void**)&dev_number, sizeof(float));
cudaMemcpy(dev_otvchislo, &otvchislo, sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(dev_number, &number, sizeof(float), cudaMemcpyHostToDevice);
float mas[33792];
float *dev_mas1;
randomer(mas);
cudaMalloc((void**)&dev_mas1, 33792 * sizeof(float));
cudaMemcpy(dev_mas1, &mas, 33792 * sizeof(float), cudaMemcpyHostToDevice);
vichislenie << <128, 128 >> > (dev_number, dev_otvchislo, dev_mas1);
cudaMemcpy(&mas, dev_mas1, 33792 * sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(&otvchislo, dev_otvchislo, sizeof(int), cudaMemcpyDeviceToHost);
cudaFree(dev_mas1);
cudaFree(dev_number);
cudaFree(dev_otvchislo);
i -= 1;
}
if (otvchislo == 1)
{
unsigned char otv[4] = "да";
cout << "Число k больше всех чисел в матрице? -" << otv << "n";
}
else
{
unsigned char otv[4] = "нет";
cout << "Число k больше всех чисел в матрице? -" << otv << "n";
}*/
system( "pause" );
return 0;
}
Ive been asked to write a function that merges two sorted (ascii sorted) strings without duplicates.
For example, for string1 = aabcd, and string2 = abbcdg, the end result string should be abcdg.
For some reason, the end result string doesnt allocate well, or so I think.. its not working anyway and its giving me weird characters instead of what its supposed to give.
The value of stringToReturn is always 0xfffffffe «Error reading characters of string», and inside it says «Unable to read memory»
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "bohan.h"
int main() {
char* string1;
char* string2;
char* mergedString;
string1 = (char*)malloc(MAX_TEXT + 1);
if (string1 == NULL)
return;
string2 = (char*)malloc(MAX_TEXT + 1);
if (string2 == NULL)
return;
printf("Please enter string no. 1: ");
scanf("%s", string1);
printf("Please enter string no. 2: ");
scanf("%s", string2);
mergedString = merge_strings(string1, string2);
printf("%s n", mergedString);
free(string1);
free(string2);
free(mergedString);
}
bohan.c:
#include <stdio.h>
#include <stdlib.h>
#include "bohan.h"
int checkNumberOfChars(char* text) {
int sum = 0;
if (text == NULL)
return 0;
while (*text != '')
{
sum++;
text++;
}
return sum;
}
char* merge_strings(char* text1, char* text2) {
int i;
int hasChanged;
char* stringToReturn;
if (text1 == NULL && text2 == NULL)
return NULL;
stringToReturn = (char *)malloc(checkNumberOfChars(text1) + checkNumberOfChars(text2) + 1);
if (stringToReturn == NULL)
return NULL;
for (i = 1; i <= MAX_ASCII; i++) {
hasChanged = FALSE;
if (*text1 != '' || *text2 != '') {
if (*text1 != '') {
if (i == *text1) {
*stringToReturn = i;
stringToReturn++;
hasChanged = TRUE;
while (*text1 == i)
text1++;
}
}
if (*text2 != '') {
if (i == *text2) {
if (!hasChanged) {
*stringToReturn = i;
stringToReturn++;
}
while (*text2 == i)
text2++;
}
}
}
else
break;
}
return stringToReturn;
}
bohan.h:
#ifndef DEF
#define TRUE 1
#define FALSE 0
#define MAX_TEXT 100
#define MAX_ASCII 255
int checkNumberOfChars(char *text);
char *merge_strings(char *text1, char *text2);
#endif DEF
Ive been asked to write a function that merges two sorted (ascii sorted) strings without duplicates.
For example, for string1 = aabcd, and string2 = abbcdg, the end result string should be abcdg.
For some reason, the end result string doesnt allocate well, or so I think.. its not working anyway and its giving me weird characters instead of what its supposed to give.
The value of stringToReturn is always 0xfffffffe «Error reading characters of string», and inside it says «Unable to read memory»
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "bohan.h"
int main() {
char* string1;
char* string2;
char* mergedString;
string1 = (char*)malloc(MAX_TEXT + 1);
if (string1 == NULL)
return;
string2 = (char*)malloc(MAX_TEXT + 1);
if (string2 == NULL)
return;
printf("Please enter string no. 1: ");
scanf("%s", string1);
printf("Please enter string no. 2: ");
scanf("%s", string2);
mergedString = merge_strings(string1, string2);
printf("%s n", mergedString);
free(string1);
free(string2);
free(mergedString);
}
bohan.c:
#include <stdio.h>
#include <stdlib.h>
#include "bohan.h"
int checkNumberOfChars(char* text) {
int sum = 0;
if (text == NULL)
return 0;
while (*text != '')
{
sum++;
text++;
}
return sum;
}
char* merge_strings(char* text1, char* text2) {
int i;
int hasChanged;
char* stringToReturn;
if (text1 == NULL && text2 == NULL)
return NULL;
stringToReturn = (char *)malloc(checkNumberOfChars(text1) + checkNumberOfChars(text2) + 1);
if (stringToReturn == NULL)
return NULL;
for (i = 1; i <= MAX_ASCII; i++) {
hasChanged = FALSE;
if (*text1 != '' || *text2 != '') {
if (*text1 != '') {
if (i == *text1) {
*stringToReturn = i;
stringToReturn++;
hasChanged = TRUE;
while (*text1 == i)
text1++;
}
}
if (*text2 != '') {
if (i == *text2) {
if (!hasChanged) {
*stringToReturn = i;
stringToReturn++;
}
while (*text2 == i)
text2++;
}
}
}
else
break;
}
return stringToReturn;
}
bohan.h:
#ifndef DEF
#define TRUE 1
#define FALSE 0
#define MAX_TEXT 100
#define MAX_ASCII 255
int checkNumberOfChars(char *text);
char *merge_strings(char *text1, char *text2);
#endif DEF
Я пытаюсь создать программу универмага для своего школьного проекта.
Я создал массив классов для продуктов, который для начала включает их названия, цены, наличие и количество приобретенных товаров.
Но почему то выскакивает ошибка
«Исключение по адресу 0x68665139 (vcruntime140d.dll) в Test project.exe:
0xC0000005: место записи нарушения прав доступа 0x86A1ECD8. »
Кроме того, я получаю сообщение об ошибке, называемое ошибкой чтения символов строки после выполнения.
Вот мой код:
#include<iostream>
#include<string>
using namespace std;
class product {
private:
int stock; //items in stock
int add_stock; //added stock
int purchased; //purchased items(reduces stock)
string name; //name of item
float price; //price of item
public:
//fuctions to input all private variables
void setstock(int x) {
stock = x;
}
void setaddstock(int x) {
add_stock = x;
}
void setpurchased(int x) {
purchased = x;
}
void setname(string x) {
name = x;
}
void setprice(float x) {
price = x;
}
//functions to output all private variables
int getstock() {
return stock;
}
int getaddstock() {
return add_stock;
}
int getpurchased() {
return purchased;
}
string getname() {
return name;
}
float getprice() {
return price;
}
//function that restocks the items
void restock() {
stock += purchased;
}
//function that deducts purchased items from stock
void destock() {
if (stock >= purchased) {
stock -= purchased;
}
else { //in case the purchase demand exceeds items in stock
cout << "nSorry we only have " << stock << "amount of leftn";
}
}
};
int main() {
int purchased;
product stuff[10]; //class array
int choice, total_qty = 0; //choice-> to choose between products,
total_qty-> total number of products purchased
char yesno; //to choose if user wants to buy anything
else (for do loop)
float total_price = 0; //total amount of money to be paid
// declaring product name and price
stuff[1].setname ("Coconut biscuits");
stuff[1].setprice (12.0);
stuff[2].setname ("Wai Wai noodles"); stuff[2].setprice (20.0);
stuff[3].setname ("Cadbury Dairy Milk"); stuff[3].setprice (45.5);
stuff[4].setname ("Lays"); stuff[4].setprice (50.0);
stuff[5].setname ("Rara Noodles"); stuff[5].setprice (18.5);
stuff[6].setname ("Khajurko Puff"); stuff[6].setprice (50.0);
stuff[7].setname ( "Nanglo Doughnut"); stuff[7].setprice (15.0);
stuff[8].setname ( "Nanglo whole-wheat bread"); stuff[8].setprice (65.0);
stuff[9].setname ("Dabur Real fruit juice"); stuff[9].setprice (30.0);
stuff[10].setname ("Coca-Cola"); stuff[10].setprice (35.5);
// declairing the number of items in stock and setting purchased = 0 for easy calculation
for (int i = 1; i <= 10; i++) {
stuff[i].setstock (100);
stuff[i].setpurchased (0);
}
// displays the menu, make purchase, repeat
cout << "What would you like to buy?nnn";
do {
for (int i = 1; i <= 10; i++) {
cout << i << ". " << stuff[i].getname() << "nn"; //displays menu in format: 1. Biscuit
}
cout << "Enter your choice: ";
cin >> choice;
cout << "nnHow many of it would you like to buy?";
cin >> purchased;
stuff[choice].setpurchased(purchased);
stuff[choice].destock(); //function for destocking
cout << "nnWould you like to buy other items?";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y');
cout << "nnn"; //line spacing, nothing cool here
//this for loop calculates total quantity and price as well as displays the receipt
for (int i = 1; i <= 10; i++) {
total_qty += stuff[i].getpurchased(); //total quantity
total_price += stuff[i].getpurchased() * stuff[i].getprice(); //total price
//only displays if stuff is purchased
if (stuff[i].getpurchased() > 0) {
//format: 1. Biscuit 4 10 40
cout << i << " " << stuff[i].getname() << " " << stuff[i].getpurchased() << " " << stuff[i].getprice() << " " << stuff[i].getpurchased()*stuff[i].getprice() << "n";
}
}
// displays total price and quantity
cout << "ntotal quantity: " << total_qty;
cout << "ntotal price: " << total_price;
return 0;
}
Эти ошибки выдаются при чтении имени файла из параметра.
«невозможно прочитать память» «ошибка чтения символов строки»
Если строка определена как введенный пользователем текст или как жесткая клавиша, то она работает нормально. Но, если часть имени файла читается из файла, соединяется и затем передается через параметр, эти ошибки выдаются.
Я пробовал как с, так и без .c_str()
После удаления некоторых пустых мест в текстовом файле, это теперь работает в Windows, но не в Linux?
void batch_helper()
{
//batch
vector <string> field_reports;
ifstream field_report_batch;
field_report_batch.open("OCR_batch.txt");
string line;
while (true) { //fill stack with batches
getline(field_report_batch, line);
if (line.empty() || !field_report_batch || field_report_batch.fail())
break;
field_reports.push_back(line);
}
field_report_batch.close();
for (unsigned int i = 0; i < field_reports.size(); i++) {
parse_file("timesheets_we" + field_reports[i] + "_batch_export.csv"); //this does not work
//parse_file("timesheets_we20121221_batch_export.csv"); //this works
}
}void parse_file(const string timecard_WE)
{
//count records
int timecard_count = 0;
string line;
//test input file
ifstream timecard_test;
timecard_test.open(timecard_WE.c_str());
getline(timecard_test, line); //burn header
while (true){
getline(timecard_test, line); //read in row_n
if (!timecard_test || timecard_test.fail())
break;
timecard_count++;
}
timecard_test.close();
line.clear();
}
Похожая проблема, опубликованная в stackoverflow: Вот, проблема заключалась в скрытом пустом месте или беспорядочном конце строки символа. Я проверил на наличие пробелов, но пока не нашел их.
Я попробую это:
while (true) {
if (line.back() == '\r' || line.back() == '\n') {
test_log << "pop: " << line.back() << "\r\n";
line.pop_back();
}
}
полученный файл
20120615
поп:
20120622
поп:
20120629
поп:
20120706
поп:
20120713
поп:
20120720
поп:
20120727
поп:
20120803
поп:
20120810
поп:
20120817
поп:
20120824
поп:
20120831
поп:
20120907
поп:
20120914
поп:
20120921
поп:
20120928
поп:
20121005
поп:
20121012
поп:
20121019
поп:
20121026
поп:
20121102
поп:
20121109
поп:
20121116
поп:
20121123
поп:
20121130
поп:
20121207
поп:
20121214
поп:
20121221
поп:
timesheets_we20120615_batch_export.csv BREAK
timesheets_we20120622_batch_export.csv BREAK
timesheets_we20120629_batch_export.csv BREAK
timesheets_we20120706_batch_export.csv BREAK
timesheets_we20120713_batch_export.csv BREAK
timesheets_we20120720_batch_export.csv BREAK
timesheets_we20120727_batch_export.csv BREAK
timesheets_we20120803_batch_export.csv BREAK
timesheets_we20120810_batch_export.csv BREAK
timesheets_we20120817_batch_export.csv BREAK
timesheets_we20120824_batch_export.csv BREAK
timesheets_we20120831_batch_export.csv BREAK
timesheets_we20120907_batch_export.csv BREAK
timesheets_we20120914_batch_export.csv BREAK
timesheets_we20120921_batch_export.csv BREAK
timesheets_we20120928_batch_export.csv BREAK
timesheets_we20121005_batch_export.csv BREAK
timesheets_we20121012_batch_export.csv BREAK
ПЕРЕРЫВЫ в файле журнала — это конец файловых разрывов.
0
Решение
Решение простое и состоит из двух частей:
ЧАСТЬ I
в текстовом файле, из которого я читаю частичные имена файлов и затем объединяю их в полное имя, после некоторого текста было пустое место. Я открыл файл, «выбрать все», а затем вручную удалил конечные пробелы.
ЧАСТЬ II:
это исправлено пока (верно)
{ if (line.back() == '\r' || line.back() == '\n') line.pop_back();}
комбинированное решение:
while (true) { if (line.back() == '\r' || line.back() == '\n' || line.back() == ' ') line.pop_back();}
0