C ++插入数字直到某个符号

时间:2011-09-28 16:21:27

标签: c++ arrays variables

我试着编写一个代码,要求我逐个输入数字,当插入某个字符时(在这种情况下为'x'),它会停止循环。但当我插入该字符时,它开始用“插入号码”向我发送垃圾邮件。我认为错误在于我正在尝试在int数组中插入一个char,但我想不出办法解决它。

long int numbers[100]={0};
char h='y';
int index=0;
do
{
    cout << "Insert Number : ";
    cin >> numbers[index];
    h=(char)numbers[index];
    index++;
}
while(h!='x');

4 个答案:

答案 0 :(得分:2)

这是因为“x”不是数字而cin >> numbers[index];操作失败,而不消耗该数据。所以循环继续,得到相同的x,再次失败,一切都重新开始。您可以检查输入操作的结果,如下所示:

#include <iostream>

using namespace std;

int main ()
{
    long int numbers[100]={0};
    char h='y';
    int index=0;
    do
    {
        cout << "Insert Number : ";
        if (cin >> numbers[index])
        {
            h=(char)numbers[index];
            index++;
        }
        else
        {
            cout << "Hey, that was not a number! Bye." << endl;
            break;
        }
    }
    while(h!='x');
}

答案 1 :(得分:0)

你应该写一个循环:

while(cin >> numbers[index]) 
   index++;

它将读取所有整数,直到您输入一些无效输入,无论是'x'还是任何其他字符。现在,如果你想跳过所有无效输入并继续读取整数(可能是在无效输入之后),并且只想考虑从'x'退出循环,那么用另一个循环包装上面的循环:

char ch;
do
{
   while(cin >> numbers[index]) 
       index++;
   cin.clear(); //clear the error flags, so you can use cin to continue reading
   cin >> ch; //read the invalid character
} while(ch != 'x');

一条建议:更喜欢使用std::vector<long int>而不是long int numbers[100]。如果用户输入超过100个整数,那么您的程序将被破坏。

答案 2 :(得分:0)

因为你试图读取一个整数,任何不是数字的字符都不能转换成数字并且会堵塞输入 - 你会收到一个错误而坏字符不会从流中删除。下次你尝试阅读时,你会得到同样的错误。

答案 3 :(得分:0)

如果您需要数字或字符串,请始终将输入作为字符串读取,如果字符串不是“x”,请尝试将其转换为数字:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>    

int main(int argc, char *argv[])
{
    std::vector<long int> numbers;
    std::string line;
    while(std::getline(std::cin, line) && line != "x") {
        std::istringstream input(line);
        long int value; 
        // Check that there is only a number with nothing else after
        if((input >> value) && input.get() == std::char_traits<char>::eof()) {
            numbers.push_back(value);
        } else {
            std::cout << "Invalid Entry, please retry" << std::endl;
        }
    }

    //...

    return 0;
}
相关问题