作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是编程新手,找不到问题的答案。
这是我必须打开我的程序并在终端上运行它时读取我想要的文本文件的代码:
using namespace std;
int main(int argc, string *argv[])
{
string fileName;
getline(cin, fileName);
ifstream infile(fileName.c_str());
int total[26] = {0};
if (!infile)
{
cout << "Error opening file" << endl;
return 0;
}
char b;
while (infile.get(b))
{
if (isalpha(b))
{
b = toupper(b);
int index = b - 'A';
total[index]++;
}
}
我可以运行该程序并通过终端输入我想打开的文件,但我教师的程序可以通过在终端中输入以下命令来打开该文件:
a.out < text.txt
当我使用 getline 而不是使用 fstream 时,它读取文件而不是整个文件(直到到达 EOF)。我不确定我应该如何编写代码。 (作业已提交,仅供本人引用)
最佳答案
当有人使用 <
进行重定向时字符,该文件成为标准输入。所以cin
将包含 text.txt
的内容.由于 cin 是 istream
你可以这样做:
while (cin.get(b)) {
// what you've got now...
}
关于c++ - 如何通过键入 "a.out < textfilename.txt"让 a.out 文件通过终端读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158266/
我是一名优秀的程序员,十分优秀!