我正在嘗試計算一串空格分隔的整數中正數、負數和零的數量。輸入字串中的整數個數由用戶指定。
代碼編譯得很好,但是每次我嘗試運行它時,它都會因錯誤“除錯斷言失敗。...運算式:字串下標超出范圍”而崩潰。
#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 ;
}
}
uj5u.com熱心網友回復:
首先std::cin >> some_string_var將在它找到的第一個空白字符處停止,因此使用它來搜索分隔單詞的空格幾乎沒有意義。
您最好只讀取整數并將它們直接與零進行比較。以下是您可以在代碼上使用 MNC(最少必要更改)的方法:
#include <iostream>
int main() {
int i = 0;
int n;
int positives = 0;
int negatives = 0;
int zeros = 0;
int value;
std::cin >> n;
while (i < n) {
std::cin >> value;
if (value > 0)
positives ;
else if (value < 0)
negatives ;
else
zeros ;
i ;
}
std::cout << "p=" << positives << ", n=" << negatives << ", z=" << zeros << '\n';
}
下面是一個示例運行,請記住,初始4值是一個計數,而不是其中一個值:
pax:~> ./prog
4
0 1 2 -99
p=2, n=1, z=1
如果你正在尋找一些強大的東西,你可以使用這樣的東西:
#include <iostream>
int main() {
int quant, pos = 0, neg = 0, zer = 0, value;
std::cout << "How many input values? ";
if (! (std::cin >> quant )) {
std::cout << "\n*** Invalid input.\n";
return 1;
}
if (quant < 0) {
std::cout << "\n*** Negative quantity input.\n";
return 1;
}
for (int count = 1; count <= quant; count) {
std::cout << "Enter value #" << count << ": ";
if (! (std::cin >> value )) {
std::cout << "\n*** Invalid input.\n";
return 1;
}
if (value > 0.0)
pos ;
else if (value < 0.0)
neg ;
else
zer ;
}
std::cout << "Positive value count: " << pos << '\n';
std::cout << "Negative value count: " << neg << '\n';
std::cout << "Zero value count: " << zer << '\n';
}
它在與用戶交流時更加用戶友好(無論是在請求的內容方面,還是在生成的結果方面)。它在檢測錯誤輸入方面也更加強大。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438330.html
