标准输入,而循环不会退出 c++
Standard input while loop won't exit c++
我正在尝试从标准输入([a.out <text.txt]在unix中读取),并且我使用了以下两个代码块:>
int main(){
while (!cin.eof()){ReadFunction()}
OutputFunction();}
和
int main(){
char c;
while (cin.getchar(c)){ReadFunction()}
OutputFunction();}
这两个循环都正确执行读取函数,但它们都没有退出循环并执行输出函数。如何从标准输入中逐个字符读取,然后执行输出函数?
我认为这可能是您的 ReadFunction() 中的一个问题。如果不读取字符,流将不会前进,并且会卡在循环中。
以下代码有效:-
#include <iostream>
#include <string>
using namespace std;
string s;
void ReadFunction()
{
char a;
cin >> a;
s = s + a;
}
void OutputFunction()
{
cout <<"Output : n" << s;
}
int main()
{
while (!cin.eof()){ReadFunction();}
OutputFunction();
}
已知
cin.eof()
是不可信的。如果经常会返回不准确的结果。无论哪种方式,都建议您从文件中复制所有数据(您说这是您的标准输入),然后从中获取字符。我建议使用 std::stringstream 来保存文件中的数据,然后使用 std::getline()。我没有编写Unix的经验,但您通常可以尝试这样的事情:
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string strData;
std::stringstream ssData;
while (std::getline(in /*Your input stream*/, strData))
ssData << strData;
ssData.str().c_str(); // Your c-style string
std::cout << (ssData.str())[0]; // Write first char
return 0;
}
至于为什么你的while循环没有退出可能与暗示有关,但你可以考虑将其作为一种替代方案。
我能想到的最简单的方法是使用如下所示的东西
#include <cstdio>
int main() {
char c;
while((c = getchar()) != EOF) { // test if it is the end of the file
// do work
}
// do more work after the end of the file
return 0;
}
与您的唯一真正的区别是,上面的代码测试c
以查看它是否是文件的末尾。然后像./a.out < test.txt
这样的东西应该起作用。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何让LLDB在成功时退出,在失败时等待
- C++控制台应用程序阻止退出
- 程序在执行程序的其余部分之前退出
- 构造函数在退出函数时无法初始化一个参数
- 为什么异常不退出程序?
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 退出简单while循环时出现问题
- 使用vscode调试时,GDB意外退出
- pclose() 不会给我进程退出代码
- 为什么系统函数总是在C++中返回已转移的退出状态?
- C++从另一个函数退出函数
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- C++逗号分隔的输入数组代码过早退出
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- 为什么 C++ 中的以下结构声明会导致退出 127?
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 进程退出,返回值3221226356写入系统( "cls" )。(已解决)