我目前正在尝试编写将用户输入作为字符串的代码,然后在需要时将它们转换为整数。如果用户决定输入exit
,则程序应继续调用函数。以下是我到目前为止的情况:
void printArray(string string_array[], int size){
for (int i = 0; i < size; i++){
cout << string_array[i];
}
}
void a_func(){
string string_array[10];
string user_input;
while (user_input != "exit"){
cout << "Please enter a number between 0 - 100: ";
cin >> user_input;
if (stoi(user_input) < 0 || stoi(user_input) > 100){
cout << "Error, please re-enter the number between 0 - 100: ";
cin >> user_input;
}
else if (user_input == "exit"){
printArray(string_array, 10);
}
int array_index = stoi(user_input) / 10;
string_array[array_index] = "*";
}
但是,当我测试程序时,如果我输入exit
,控制台就会中止该程序。有没有办法让我进入退出,然后程序调用{{1}}?
答案 0 :(得分:0)
我认为代码中的这种变化将解决问题。请尝试使用此代码:
void printArray(string string_array[], int size){
for (int i = 0; i < size; i++){
cout << string_array[i];
}
}
void a_func(){
string string_array[10];
string user_input;
while (user_input != "exit"){
cout << "Please enter a number between 0 - 100: ";
cin >> user_input;
if (user_input == "exit"){
printArray(string_array, 10);
}
else if (stoi(user_input) < 0 || stoi(user_input) > 100){
cout << "Error, please re-enter the number between 0 - 100: ";
cin >> user_input;
int array_index = stoi(user_input) / 10;
string_array[array_index] = "*";
}
}
}
希望这有帮助
答案 1 :(得分:0)
stoi不接受非数字。试试这个:
#include <iostream>
using namespace std;
void printArray(string string_array[], int size){
for (int i = 0; i < size; i++){
cout << string_array[i];
}
}
void a_func(){
string string_array[10];
string user_input;
while (user_input != "exit"){
cout << "Please enter a number between 0 - 100: ";
cin >> user_input;
//cout << "You have printed " << user_input << endl;
bool isNumber = true;
for(string::const_iterator k = user_input.begin(); k != user_input.end(); ++k) {
if (isdigit(*k) == false) {
isNumber = false;
break;
}
}
if (isNumber) {
int number = stoi(user_input);
if (number < 0 || number > 100){
cout << "Error, please re-enter the number between 0 - 100: ";
continue;
} else {
int array_index = stoi(user_input) / 10;
string_array[array_index] = "*";
}
} else if (user_input == "exit"){
printArray(string_array, 10);
break;
} else {
// Not a number and not "exit"; do nothing?
}
}
}
int main() {
a_func();
return 0;
}