使用文件代替用户输入的C++ cin

4

我已经查过了所有可能的资源,但似乎找不到一个确切的答案。也许这显而易见,但我还是对C++比较陌生。

我有以下可运行的主函数:

int main()
{
    char firstChar, secondChar;
    cin >> firstChar;
    cin >> secondChar;
    cout << firstChar << " " << secondChar;

    system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
    return 0;
}

这将导致控制台等待输入。用户输入了一些内容,在本例中是(test)。输出结果为:

( t

我希望将此更改为从文件中获取输入,并且可以针对每行执行相同的方式,而不仅仅是执行一次。
我尝试了以下多种变化:
int main(int argc, char* argv[])
{
    ifstream filename(argv[0]);
    string line;
    char firstChar, secondChar;
    while (getline(filename, line))
    {
        cin >> firstChar;  // instead of getting a user input I want firstChar from the first line of the file.
        cin >> secondChar; // Same concept here.
        cout << firstChar << " " << secondChar;
    }

    system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
    return 0;
}

这仅仅针对文件中的每一行运行了一次while循环,但仍需要在控制台中输入,并且无法以任何方式操作文件中的数据。
文件内容:
(test)
(fail)

期望的自动输出(不需要用户手动输入“(test)”和“(fail)”):
( t
( f

我已经添加了一个答案,但除非您向我们展示一个输入文件的示例,否则我只能猜测它的格式。 - const_ref
3个回答

3

最终编辑

看到输入,我会做如下操作:

int main(int argc, char* argv[])
{
    ifstream exprFile(argv[1]); // argv[0] is the exe, not the file ;)
    string singleExpr;
    while (getline(exprFile, singleExpr)) // Gets a full line from the file
    {
        // do something with this string now
        if(singleExpr == "( test )")
        {

        }
        else if(singleExpr == "( fail )") etc....
    }

    return 0;
}

你已知道文件的完整输入,因此可以一次将整个字符串进行测试,而不是逐个字符地测试。在获得该字符串后,只需相应地进行操作。

每行都有一个表达式,但它们可能相当复杂,因此不仅仅是x + y那么简单。还可能有嵌套的表达式等等。以前我只是通过使用cin >> charVariable提取字符来处理这个问题,这将提取最左边的字符。但当它是一个字符串而不是输入时,一切都会改变。 - leigero
请编辑您的问题以展示文件布局的示例。 - const_ref
使用 cin >> charVariable 会导致控制台等待用户输入。我想使用同样的概念来处理现有的字符串。类似于 singleExpr >> charVariable,但这并不起作用。 - leigero
不过你可以逐个字符地迭代字符串。请将您的文件复制粘贴到这里,我会相应地编辑我的答案。 - const_ref
@leigero,请查看我的编辑,以逐个字符迭代字符串。这似乎是您所期望的行为。 - const_ref

0
你可以这样做:
int main(int argc, char* argv[])
{
    ifstream filename(argv[0]);
    string line;
    char firstChar, secondChar;
    while (getline(filename, line))
    {
        istringstream strm(line);
        strm >> firstChar;
        strm >> secondChar;
        cout << firstChar << " " << secondChar;
    }

    system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
    return 0;
}

有趣的是看到 filename(argv[0]) :) - undefined

0
流提取运算符或'>>'会从流中读取,直到找到空格为止。 在C++中,cin和cout分别是类型为istream和ostream的流。在您的示例中,exprFile是一个istream,当文件打开时,它成功连接到您提到的文件。要从流中逐个获取一个字符,可以按照以下方式进行操作,
char paren;
paren = cin.get(); //For the cin stream.
paren = exprFile.get(); //for the exprStream stream, depending on your choice

要获取更多信息,请浏览这个


cppreference.com是首选的参考网站。你提到的那个网站相当差劲。 - const_ref
通过编辑后的问题文件内容 paren = filename.get(); 打印出一个美元符号。该文件的内容为 (test) - leigero
对我来说可以运行。我得到的是(而不是$。 - Abhishek Bagchi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接