有没有更好的方法可以接收此输入? C ++

当前仅尝试编辑一些基本输入以摆脱单数“。”。在一行的开头。 但是,这仅在我强制EOF时起作用。我在uni网站上对此作业的提交评论似乎陷入了while循环中,并且没有输出结果。输入量最多可以达到1000行,我似乎想不出如何最好地接收输入而不被卡住。 main.cpp如下:

示例输入和输出为:

Input:
..hello
.hello
hello

Output:
.hello
hello
hello
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

int main(int argc,char *argv[])
{
    string inputLine;
    vector<string> vect;
    string s;
    string temp;

    while (getline(cin,s)) {
        vect.push_back(s);
    }

    for (int i = 0; i < (int)vect.size(); i++) {
        temp = vect[i];
        if (temp[0] == '.') {
            for (int k = 0; k < (int)temp.length(); k++) {
                temp[k] = temp[k + 1];
            }
        }
        vect[i] = temp;
    }

    for (int j = 0; j < (int)vect.size(); j++) {
        cout << vect[j] << endl;
    }



    return 0;
}
gsephiroth 回答:有没有更好的方法可以接收此输入? C ++

程序的测试人员可能正在打开管道,并在发送第二行之前等待程序输出第一行。一例僵局。

如果要忽略.字符,可以使用std::basic_istream::peek检查行是否以该字符开头,然后简单地std::basic_istream::ignore。您可能还想使用std::endl刷新每一行的输出。

#include <string>
#include <iostream>

int main() {
    std::string line;
    while(std::cin) {
        if(std::cin.peek() == '.')
            std::cin.ignore();
        if(std::getline(std::cin,line))
            std::cout << line << std::endl;
    }
}
本文链接:https://www.f2er.com/3165401.html

大家都在问