对字符串使用cin和getline
Use of cin and getline for strings
我最近在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
并将其设置为使用printf
或puts
来提示,然后使用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个是否连续。
如果你不需要一个新的解决方案,并希望得到你的代码修复,告诉我的评论
相关文章:
- Getline(cin,str)的奇怪输出
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- C++ getline(cin,变量)行为不端.网站上没有任何解决方案有帮助
- 由于 getline(cin,s) 导致的 SIGABRT 错误
- 为什么我们需要在getline(cin,string)之前使用cin.ignore()
- 在C 中使用两个GetLine(CIN,S)
- 使用 getline(cin,n) 输入;没有打印第一个输入,我没有使用 CIN >> 在任何地方输入
- 为什么必须键入 getline(cin,字符串)两次
- 无法删除 txt 文件中 getline(cin , (变量)) 之后的下一行
- getline(cin,_string);
- 当使用getline(cin,string)时,CIN会自动获取其值而不询问
- 我的程序跳过getline(cin,CustInfo),进入CustomerInfo函数中的City.我该怎么修
- Using cin AFTER getline(cin, string)
- 如何正确使用"getline(cin, input);"
- 关于getline(cin,string)的C++快速问题
- getline(cin,s1)没有提示我输入
- 为什么 cin.ignore() 后面的 getline(cin, var) 不读取字符串的第一个字符?
- 为什么getline(cin,string_name)在我第一次在循环中使用它时会创建一个空字符串
- getline(cin,aString)接收输入而不输入另一个值
- getline(cin,string)与cin.ignore()一起不工作