【问题标题】:C++ code to get line of file and read the second word of the line?C ++代码获取文件行并读取该行的第二个单词?
【发布时间】:2009-05-30 22:57:44
【问题描述】:
#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");
}

问题是:有人可以向我解释一下吗?我不明白它在做什么,我的意思是我明白了这个概念,但每一行都在做什么?

【问题讨论】:

  • 请修正您的代码以在每行前使用 4 个空格。这是作业吗?
  • 修复了格式。 @H4cKL0rD,请记住在将代码粘贴到 Stack Overflow 时通过缩进四个空格来格式化代码。

标签: c++


【解决方案1】:

你想要每一行的注释

// 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)
}

【讨论】:

  • 除非在尝试查找字符串的最后一个单词时,否则此方法有效。访问line[i+1] 会在运行时崩溃。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    也许这会有所帮助:

    // 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
        }       
      }
    }
    

    例如,当行以空格开头时,上面的算法会失败,因此这里有许多关于需要处理的 in-data 假设,例如如果索引无效或 in-line 为空,则不进行处理.如果函数失败,也会丢失最后一个返回值。

    【讨论】:

      【解决方案4】:

      您有 C++ 的交互式调试器吗?例如,如果将此代码加载到 Microsoft Visual C++ 中,则可以一次单步执行一个语句,在执行过程中检查每个变量的值。这是了解新代码在细节级别的作用的好方法。

      【讨论】:

        【解决方案5】:

        有一个叫做 strWord 的函数可以从一个句子中取出一个带有任何索引的单词并返回它。

        主程序打开一个文件,每行包含一个 id 和另一个单词,并准备好从中读取。

        然后它向用户请求一个 id,检查该 id 是否是文件中任何行中的第一个单词。如果是,则从该行中取出第二个单词并打印出来。

        就是这样。询问您是否对特定行或一堆行有问题。

        或者按照 Greg 的建议,使用调试器。这将是理解任何逻辑的最简单方法。

        【讨论】:

          猜你喜欢
          • 2019-06-27
          • 2017-05-17
          • 1970-01-01
          • 2016-06-18
          • 2019-07-12
          • 1970-01-01
          • 1970-01-01
          • 2014-10-18
          • 2013-10-07
          相关资源
          最近更新 更多