문제

This is my function at the moment

long long int File::Getline3(int user1, long long int user3)
{
std::string filename = std::to_string(user1);

std::ifstream fin(filename + ".txt");
fin.getline (line1, 5);
fin.getline (line2, 5);
fin.getline (line3, 20);
fin.close();

user3 = (atoi(line3));

return user3;
}

Seems to return a most of the numbers, but not all, and in a jumbled up format.

Not sure if my error lies in reading the line (getline) or converting it (atoi) or returning it.

(line1, line2 and line3 char declared in header file)

Line 3 is 16 digits long.

도움이 되었습니까?

해결책

I think for long long int it should not be atoi, but strtoll:

long long int strtoll(const char *nptr, char **endptr, int base);

supposingly line3 is a string, you might use it as:

char* endptr = NULL;
user3 = strtoll(line3.c_str(), &endptr, 10);

and sice you marked it as c++ you also can use: http://www.cplusplus.com/reference/string/stoll/

edit after your comment: strtoll takes a const char* and converts its content into a long long int. If endptr is not NULL, strtoll() stores the address of the first invalid character in *endptr. You also can specify the base for the number.

You did (atoi(line3)); but atoi also expects a const char* so I supposed that line3 must be a std::string (due to the way you use it) that's why I gave a shot in the dark with the c_str() to get the actual data of the string, instead of the object itself..

Instead of atoi you can use of course atoll for long long stuff :)

다른 팁

Read char by char from left end of the string as and compute and add to a cumulative as per place value.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top