简体   繁体   English

我无法从文本文件中读取行吗?

[英]I'm having trouble reading in lines from a text file?

I want to read in a line from a text file, store the line in an array of strings to later display the line numbers a word can be found on, and also break down the line into words for marking how many times unique words come up. 我想从文本文件中读取一行,将该行存储在字符串数组中,以便以后显示可以在其上找到一个单词的行号,还可以将该行分解为多个单词,以标记出现多少次唯一单词。 I have successfully been able to break down the lines word by word and mark the frequency in which they appear but I'm struggling with storing the line in an array of strings so that I can use it later. 我已经能够成功地逐行分解行并标记行出现的频率,但是我正努力将行存储在字符串数组中,以便以后使用。

void get_word(istream& in_stream, string& w,
              list<string> &wordlist, int& lineCount, string *line)
{

  string t;
  getline(in_stream,t);

  for (int j=0; t[j]; j++)
    t[j] = tolower(t[j]);

  line = &t;
  istringstream iss(t);
  string word;
  while(iss >> word) 
  {
    insert_word(word, wordlist);
  }

}

So far this is what I have and no matter what I try to do with the line where I try to assign the string "t" to the "line" array that's being pointed to it doesn't put anything in the array, I think I'm just completely missing something. 到目前为止,这就是我所拥有的,无论我如何尝试对将字符串“ t”分配给所指向的“ line”数组的行进行处理,我认为都不会在数组中放入任何内容我只是完全缺少一些东西。 line is initialized as: 行初始化为:

string line[0];

First of all, string line[0] gives you an array of no strings. 首先, string line[0]给您一个没有字符串的数组。 That's not likely to be what you intended. 那不可能是您想要的。 Why not simply string line ? 为什么不简单地使用string line That's one string. 那是一个字符串。 You'd pass a pointer to that string into your function, with &line . 您可以使用&line将指向该字符串的指针传递给函数。

Secondly, line = &t replaces the input pointer with a pointer to the local variable. 其次, line = &t将输入指针替换为指向局部变量的指针。 This information is lost once the function ends. 功能结束后,该信息将丢失。 If you write *line = t then you are instead setting "the string that line points to" to the value of "the string t ". 如果您写*line = t则将“ line指向的字符串”设置为“字符串t ”的值。

Ideally you'd avoid the "out argument" and just return the string you want, though. 理想情况下,您应避免使用“ out参数”,而只返回所需的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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