遍历字符串 c++ 的代码出现字符串下标超出范围错误
我正在尝试计算一串空格分隔的整数中正数、负数和零的数量。输入字符串中的整数个数由用户指定。
代码编译得很好,但是每次我尝试运行它时,它都会崩溃并显示错误“调试断言失败。...表达式:字符串下标超出范围”。
#include <iostream>
#include <string>
#include <iomanip>
int main() {
int i = 0;
int n, x;
int positives = 0;
int negatives = 0;
int zeros = 0;
std::string ip;
char space = ' ';
std::cin >> n;
std::cin >> ip;
while (i < n) {
if (ip[i] != space) {
x = (ip[i]);
if (x > 0) {
positives++;
}
else if (x < 0) {
negatives++;
}
else if (x == 0) {
zeros++;
}
}
i++;
}
}
I am trying to count the count the number of positive numbers, negative numbers and zeros in a string of space separated integers. The number of integers in the input string is specified by the user.
The code compiles fine, however every time I try to run it, it crashes with the error "Debug Assertion Failed. ... Expression: String subscript out of range".
#include <iostream>
#include <string>
#include <iomanip>
int main() {
int i = 0;
int n, x;
int positives = 0;
int negatives = 0;
int zeros = 0;
std::string ip;
char space = ' ';
std::cin >> n;
std::cin >> ip;
while (i < n) {
if (ip[i] != space) {
x = (ip[i]);
if (x > 0) {
positives++;
}
else if (x < 0) {
negatives++;
}
else if (x == 0) {
zeros++;
}
}
i++;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先
std::cin>> some_string_var
将在它找到的第一个空白字符处停止,因此使用它来搜索分隔单词的空格没有什么意义。您最好只读取整数并将它们直接与零进行比较。以下是您如何在代码中使用 MNC(最少必要的更改):
下面是一个示例运行,请记住初始的
4
是一个计数而不是其中一个值:如果您正在查找对于稍微健壮的东西,您可以使用这样的东西:
与用户通信时更加用户友好(无论是在请求的内容还是生成的结果方面)。它在检测不良输入方面也更加稳健。
For a start
std::cin >> some_string_var
is going to stop at the first white space character it finds, so there's little point in using that to search for spaces separating words.You would be better off just reading in integers and just comparing them directly with zero. Here's how you could do with with the MNC (minimum necessary change) on your code:
A sample run follows, keeping in mind the initial
4
is a count rather than one of the values:If you were looking for something a little robust, you could use something like this:
It's a little more user friendly on communicating with the user (both in terms of what is requested, and the results generated). It's also a little more robust in detecting bad input.