我正在尝试从标准输入(unix中的a.out< text.txt )中读取,并且使用了以下两个代码块:
int main(){
while (!cin.eof()){ReadFunction()}
OutputFunction();}和
int main(){
char c;
while (cin.getchar(c)){ReadFunction()}
OutputFunction();}这两个循环都正确地执行了read函数,但它们都没有退出循环并执行输出函数。如何从标准输入中逐字读取,然后执行输出功能?
发布于 2016-01-31 03:42:45
我认为这可能是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();
}发布于 2016-01-31 03:42:09
众所周知,cin.eof()是不可信赖的。如果能经常返回一个不准确的结果。无论哪种方式,建议您从文件中复制所有数据(您说这是您的标准输入),然后从该文件中获取字符。我建议使用std::getline流来保存文件中的数据,然后使用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循环不存在的原因,可能与实现有关,但您可能会认为这是一种替代。
发布于 2016-01-31 03:44:49
我能想到的最简单的方法是使用以下方法
#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这样的东西应该可以工作。
https://stackoverflow.com/questions/35109820
复制相似问题