对字符串使用cin和getline

Use of cin and getline for strings

本文关键字:getline cin 字符串      更新时间:2023-10-16

我最近在C++做一个问题:

写一个程序来计算一串5位数字是否连续数字。为了方便起见,假设数字是字符串:

string numbers = "10-9-8-7-6";

确保您的代码也适用于以下序列:

string numbers = "1-2-3-4-5";

我解决了它,但是我看到当我使用cin作为字符串时,控制台窗口抛出了一些异常&我没有执行这个程序,但是用getline代替它,它工作得很好。

谁能给我解释一下背后的原因,因为逻辑上两者都应该正常工作。

程序是:

#include<iostream>
#include<string>
using namespace std;
void change(int x, int y, int &inc, int &dec)
{
    if (x - y == 1)
        ++dec;
    else if (y - x == 1)
        ++inc;
}
int main()
{
    string s = "", snum = "";
    cout << "enter 5 nos and use '-' to separate them: ";
    cin >> s;
    int i = 0, x = 0, y = 0, inc = 0, dec = 0;
    for (char &ch : s)
    {
        if (ch == '-')
        {
            ++i;
            if (i == 1)
            {
                y = stoi(snum);
                cout << y << endl;
            }
            else
            {
                x = y;
                y = stoi(snum);
                cout << x << " " << y << endl;
                change(x, y, inc, dec);
            }
            snum = "";
        }
        else
            snum += ch;
    }
    x = y;
    y = stoi(snum);
    cout << x << " " << y << endl;
    change(x, y, inc, dec);
    if (inc == 4 || dec == 4)
        cout << "ORDERED";
    else
        cout << "UNORDERED";
    return 0;
}

如果您必须同时输入所有内容,例如:

10 9 8 7 6

全部在一行上,那么cin不同时记录所有这些。例如,对于cin,它只接受空格(" ")之前的字符。然而,Getline采用整条线并使用它。做同样事情的另一种方法是使用cstdio library并将其设置为使用printfputs来提示,然后使用gets从看跌提示收集所有信息。这就是我认为它工作的原因。

的例子:

cstdio图书馆

char string[50];
printf("Enter a string of text");
gets(string);
cout << string << endl;
*编辑

在下面的评论之后,我意识到你在问什么,如果你假设数字是字符串,它们用连字符分隔,没有空格,那么它应该工作得很好。它不应该是由别的东西引起的问题吗?

如果你的代码中有空格,那么我在上面写的EDIT将是一个简单的解决方案。

如果您需要获得格式化字符串,我建议您这样使用scanf:

if( 5 == scanf("%d-%d-%d-%d-%d", &a, &b, &c, &d, &e) )
      //welldone
      // work with above 5 int easily :)
else
      // Please enter again 

这样你就完全不用处理string了,生活也会更轻松。你可以很容易地检查这5个是否连续。

如果你不需要一个新的解决方案,并希望得到你的代码修复,告诉我的评论