C++ cin 与文件而不是用户输入



我已经查找了所有资源的感觉,但我似乎找不到这个问题的可靠答案。也许很明显,我对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) and (fail)

( t
( f

最终编辑

看到输入后,我会做这样的事情

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;
}

您知道文件中的完整输入是什么,因此您可以一次测试整个字符串,而不是逐个字符测试。然后,一旦你有了这个字符串

流提取运算符或">>"将从流中读取,直到找到空格。在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

要获取更多信息,请浏览此内容

你可以这样做:

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;
}

最新更新