gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:19:17 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com