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

标签 c++ vector stdvector

目前只是尝试编辑一些基本输入以摆脱单数“。”在一行的开头。 但是,这仅在我强制 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;
}

最佳答案

您的程序的测试人员可能正在打开一个管道并等待您的程序输出第一行,然后再发送第二行。一个死锁案例。

如果你想忽略 . 字符你可以使用 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;
    }
}

关于c++ - 有没有更好的方法可以接收此输入? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697036/

相关文章:

c++ - 使用 ofstream 在 cython 中写下二维 vector

c++ - 获取元素在 std::vector 中的位置

c++ - 为什么这段代码以无限循环结束,从 std::cin 读取

抽象类的C++工厂方法模式

具有 2 个键的 C++ 映射,因此可以使用任何 1 个键来获取值

c++ - 正则表达式从 netsh wlan 获取 MAC 地址

c++ - 图像的opencv中以下两行之间有什么区别

c++ 使用空指针访问静态成员

c++ - 如何最好地填充 vector (避免浪费内存以及不必要的分配和取消分配)?

c++ - std::vector 向下调整大小