Parsing integers from a string

I am parsing the input text file. If I take the input string one line at a time using getline (), is there any way that I can search the string to get an integer? I was thinking of something like getNextInt () in Java.

I know that there should be 2 numbers in this input line; however, these values ​​will be separated by one or more space characters, so I cannot just go to a specific position.

+3
source share
5 answers

If it has only spaces and integers, just try something like this:

int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;

or simpler:

int i1, i2;
theFileStream >> i1 >> i2;
+4
source

, :
, , , .

while(inFile >> rows >> columns)
{
    // Successfully read rows and columns

    // Now remove the extra stuff on the line you do not want.
    inFile.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}

, , , - " ", ignore().

while() , : → (). , bool, stream , ( good() ).

, NOT

while(inFile.eof())

, . eof(), false ( , EOF). , , . getline() ( ), EOF. , inLine.

, . , .

while(inFile.eof())  // Should probably test good()
{
    getLine(inFile,inputline);
    if(inFile.eof()) // should probably test good()
    {
         break;
    }
}
+5

, C-ish, sscanf() C. strtol() - C.

++-ish-, , .

0

:

while (!inFile.eof()) {
    getline (inFile,inputLine);
    stringstream ss(inputLine);
    ss >> rows >> columns;
}

:

" , 1 "

(inputLine);

edit: , . , .

0

.eof() , , . , :

  • EOF , , (, getline , )
  • EOF is set even after a successful read, if the read operation was to look for the next character after the end to determine that it should stop reading (for example, after the gel of the last line, if there was no newline at the end)

In general, you should ONLY use .eof () after a failed read to check if the failure was caused by the end of the input.

Use while (std::getline(...))to scroll through the lines.

0
source

Source: https://habr.com/ru/post/1698448/


All Articles