请看下面的代码

int main()
{
    cout << "Enter numbers (-1 to stop entering; -2 to exit)" << endl;

    while(cin>>enterNumber)
    {
     numbers.push_back(enterNumber);
    }


    for(size_t size=0;size<numbers.size();size++)
    {
        cout << numbers[size] << endl;
    }
}

我在这里尝试做的是这样的
  • 输入数字列表(例如:1 2 3 4 5 6 7 8 9 0 11)
  • 将它们全部读入 vector
  • 打印它们

  • 在这里,当我按回车键时,什么也没有发生!似乎循环没有退出。当我按下回车键时如何打印值?

    更新

    我按照答案中给出的建议编辑了代码。
    int main()
    {
        cout << "Enter numbers (-1 to stop entering; -2 to exit)" << endl;
    
        std::string line;
    getline(std::cin, line);
    std::istringstream iss(line);
    while (iss >> enterNumber)
    {
        numbers.push_back(enterNumber);
    }
    
    
        for(size_t size=0;size<numbers.size();size++)
        {
            cout << numbers[size] << endl;
        }
    }
    

    但它现在给出了另一个错误
    "/usr/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
    make[1]: Entering directory `/cygdrive/c/Users/yohan/Documents/NetBeansProjects/Excersice 6'
    "/usr/bin/make"  -f nbproject/Makefile-Debug.mk dist/Debug/Cygwin-Windows/excersice_6.exe
    make[2]: Entering directory `/cygdrive/c/Users/yohan/Documents/NetBeansProjects/Excersice 6'
    mkdir -p build/Debug/Cygwin-Windows
    rm -f build/Debug/Cygwin-Windows/Multiple.o.d
    g++    -c -g -MMD -MP -MF build/Debug/Cygwin-Windows/Multiple.o.d -o build/Debug/Cygwin-Windows/Multiple.o Multiple.cpp
    Multiple.cpp: In function `int main()':
    Multiple.cpp:22: error: variable `std::istringstream iss' has initializer but incomplete type
    Multiple.cpp:60:3: warning: no newline at end of file
    make[2]: *** [build/Debug/Cygwin-Windows/Multiple.o] Error 1
    make[1]: *** [.build-conf] Error 2
    make: *** [.build-impl] Error 2
    nbproject/Makefile-Debug.mk:78: recipe for target `build/Debug/Cygwin-Windows/Multiple.o' failed
    make[2]: Leaving directory `/cygdrive/c/Users/yohan/Documents/NetBeansProjects/Excersice 6'
    nbproject/Makefile-Debug.mk:61: recipe for target `.build-conf' failed
    make[1]: Leaving directory `/cygdrive/c/Users/yohan/Documents/NetBeansProjects/Excersice 6'
    nbproject/Makefile-impl.mk:39: recipe for target `.build-impl' failed
    
    
    BUILD FAILED (exit value 2, total time: 1s)
    

    最佳答案

    使用 getline 将 cin 中的一行读入字符串。然后将该字符串放入 istringstream 。然后从该 istringstream 中读取,而不是您现在使用 cin 的位置。

    std::string line;
    getline(std::cin, line);
    std::istringstream iss(line);
    while (iss >> enterNumber)
    {
        numbers.push_back(enterNumber);
    }
    

    关于c++ - 将整行整数读入 vector ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12775920/

    10-09 07:35