C++:一次阅读一个字符,直到一行的末尾不起作用

C++: Reading in one character at a time until the end of a line not working

本文关键字:一行 不起作用 一个 一次 C++ 字符      更新时间:2023-10-16

我应该一次读取一个文本文件一个字符,每次有新行时,line应该增加一个。

所以这是代码的相关部分:

ifstream textFile.open("PATHWAY::HERE//RRER.txt");
int line = 1;
char letter;
while (textFile)
{
  //Read in letter
  textFile >> letter;
  // If you reach the end of the line
  if (letter == 'n')
  {
    line++;
    cout << line;
  }
}

由于某种原因,if 语句被完全忽略,并且永远不会打印出行。

尽管答案(到目前为止)已经正确提到了有关""的问题,但提到的方法可能不起作用。>>的原因是格式化的输入运算符将跳过空格。您必须使用std::ifstream::get读取文件

代码将如下所示:

while (textfile.get(letter))
{
            // If you reach the end of the line
    if (letter == 'n')
    {
        line++;
        cout << line;
    }
}

代码中存在一些错误:

    它是""
  • 而不是"/n"
  • 行 = 0 而不是 1
  • 您需要使用 std::ifstream::get 来读取文件

  • 删除textFile>> letter;,因为它将跳过whitespaces

所以你的代码将如下所示

ifstream textFile.open("PATHWAY::HERE//RRER.txt");
        int line = 0; // not 1
        char letter;
        while(textFile.get(letter))
            {
             // If you reach the end of the line
                if (letter == 'n')
                {
                    line++;
                    cout << line;
                }
            }
您可以使用

n字符来查找这是否是换行符

所以你的代码应该是

ifstream textFile.open("PATHWAY::HERE//RRER.txt");
  int line = 1;
   char letter;
  while (textFile)
    {
    // Read in letter
    textFile>> letter;
    // If you reach the end of the line
    if (letter == 'n')
    {
        line++;
        cout << line;
    }
}

使用 istream::get

ifstream textFile.open("PATHWAY::HERE//RRER.txt");
int line = 0;
char letter;
while(textFile.get(letter))
{
  // If you reach the end of the line
  if (letter == '/n')
  {
    line++;
    cout << line;
  }
}