简体   繁体   中英

C++ code to get line of file and read the second word of the line?

#include <iostream>
#include <string>
#include <fstream>

using namespace std ;


string strWord( int index , string line)
{
       int count = 0;
       string word;
       for ( int i = 0 ; i < line.length(); i++)
       {
           if ( line[i] == ' ' )
           {
                if ( line [i+1] != ' ')
                {

                    count ++;
                    if (  count == index)
                    {
                       return word;
                    }
                    word ="";
                }
           }
           else
           {
                word += line[i];
           }       
       }
}







int main ( )
{
    ifstream inFile ;
    inFile.open("new.txt");
    string line  , id;

    cout <<"Enter id : ";
    cin >>id;
    while(!inFile.eof() )
    {
                        getline ( inFile , line );
                        if ( strWord ( 1, line ) == id ) 
                        {
                             cout <<strWord ( 2 , line ) <<endl;
                             break;
                        }
    } 
    system("pause");
}

Question is : Can someone explain this to me I do not get what it is doing i mean i get the concept but what is each line doing?

You wanted a comment of each line

// function that returns a word from 'line' with position 'index'
// note that this is not a zero based index, first word is 1,
// second is 2 etc ..
string strWord(int index, string line)
{
    int count = 0; // number of read words
    string word; // the resulting word
    for (int i = 0 ; i < line.length(); i++) { // iterate over all characters in 'line'
        if (line[i] == ' ') { // if this character is a space we might be done reading a word from 'line'
            if (line[i+1] != ' ') { // next character is not a space, so we are done reading a word
                count++; // increase number of read words
                if (count == index) { // was this the word we were looking for?
                    return word; // yes it was, so return it
                }
                word =""; // nope it wasn't .. so reset word and start over with the next one in 'line'
            }
        }
        else { // not a space .. so append the character to 'word'
           word += line[i];
        }       
    }
}


int main( ) // main function of the program, execution starts here
{
    ifstream inFile; // construct input file stream object
    inFile.open("new.txt"); // associate the stream with file named "new.txt"
    string line, id; // 

    cout << "Enter id : "; // write "Enter id :" to console
    cin >> id; // read input from console and put the result in 'id'

    while (!inFile.eof()) { // do the following as long as there is something to read from the file
        getline(inFile, line); // read a line from the file and put the value into 'line'
    if (strWord(1, line) == id) { // if the first word in 'line' equals 'id' ..
        cout << strWord(2, line) << endl; // prints the second word in 'line'
        break; // exits the while loop
    }
    } 

    system("pause"); // pause the program (should be avoided)
}

我没有仔细阅读,但是看起来它打印出该行的第二个单词,第一个单词是用户输入的单词。

Maybe this helps:

// return word[index] from line
string strWord( int index , string line) // word index and actual line
{
  int count = 0; // current word index
  string word; // word buffer (return value)

  for ( int i = 0 ; i < line.length(); i++) // loop through each character in line
  {
    if ( line[i] == ' ' ) // if current character is a space
    {
      if ( line [i+1] != ' ')  // but next char is not space, we got a word
      {
        count ++; // incr current word index counter in line
        if (  count == index) // if count == looked for index return word
        {
          return word;
        }
        word ="";  // otherwise reset word buffer
      }
    }
    else // character is not space
    {
       word += line[i]; // add letter/digit to word buffer
    }       
  }
}

The algorithm above fails when for instance the line starts with a space so there are a number of assumptions here about the in-data that need to be addressed like no handling if the index is invalid or if the in-line is empty. There is also missing a last return value if the function fails.

Do you have an interactive debugger for C++? For example, if you load this code into Microsoft Visual C++, you can step through the program one statement at a time, inspecting the value of each variable as you go. This is a great way to learn what a new piece of code does at the detail level.

There is a function called strWord to take a word with any index from a sentence and returns it.

Main program opens a file containing an id and another word in each line and keeps it ready to be read from.

Then it asks for an id from the user, checks if the id is the first word in any of the lines in the file. If it is, then it takes the second word from that line and prints it.

That's all. Ask if you have problems with a specific line or bunch of lines.

Or as Greg suggests, go for a debugger. That would be the easiest way to understand any logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM