c++ - 从文件中读入时如何阻止空格显示为回车?

标签 c++ file input stl

void displayFile()
{
    char userInput[20];//Used to store the typed input commands from the user.
    ifstream ip("D:\\H Drive ITT\\Level 8 Degree\\Software Dev (Andrew)\\MiniProject\\about.txt");//Input from file

    string line ;//Store each line in the string
    int exit = 0;//Used to hold the value which indicates whether or not the function should end determined by the user.

    if (ip)//ip is true if the file exists.
    {}
    else
    {
        cout << "-Error_File_Not_Found" << endl;
    }


    while (!ip.eof())//Scan till end of file
    {
        ip >> line;
        cout << line << endl;

    }
    cout << "Type exit to return" << endl << endl << ">>>" ;
    do {
        cin >> userInput;
        if (strcmp(userInput, "exit") == 0 || strcmp(userInput, "EXIT") == 0 || strcmp(userInput, "eXIT") == 0 || strcmp(userInput, "Exit") == 0)
        {
            exit = 1;
        }
        else
        {
            exit = 0;
        }

    } while (exit !=1);
    ip.close();


}

//The
//output
//displays
//like 
//this.

当代码运行时,它会接收段落并将每个单词显示在其自己的一行中。我已经看到涉及类(class)的解决方案,但我需要一个不同的解决方案,因为我还没有完成类(class)。

最佳答案

这里有两个问题。

  1. >>> 运算符不读取行,它在空白处停止。按照评论中 Ramana 的建议使用 std::getline
  2. 您错误地使用了 eof()。它返回 true after 你已经读完了文件末尾,而不是 before 你读完了。所以你的循环会重复一次太多。最好的方法是使用std::getline的返回值作为循环条件。

关于c++ - 从文件中读入时如何阻止空格显示为回车?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088059/

相关文章:

c++ - 如何在 spidermonkey 嵌入中提供 js-ctypes?

c - 在 C 中使用管道读取多条消息?

iphone - 从应用程序包读取文本文件

css - 在CSS中创建两个密码输入

java - 读取未知数量的输入

c++ - 复制对象时,带有 MSVC 2010 Debug 的 OpenMP 会生成奇怪的错误

c# - 在 C# 或 C++ 中搜索另一个音频中的音频

c++ - 使用 Visual Studio 构建 JNI dll 时出现链接错误

c# - (手动)序列化和反序列化二叉搜索树

jquery - 使用 Jqueryeach() 循环输入字段进行验证