我的代码中有错误, 这是我的代码:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''";
char ch;
int i = 0;
while (Isnumber(ch)){ //here is the error
do{
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (ch>0 || ch < 9);
}
getchar();
}
两个错误, 它说标识符未知, 和 它说变量char是uninitialazed局部变量,
答案 0 :(得分:1)
将此 while (Isnumber(ch)){
更改为do-while循环。
do{
.....
}while (Isnumber(ch))
错误是因为声明了 ch并且在初始化之前使用了它。
还包括#include <stdio.h>; for getchar();
答案 1 :(得分:0)
最好在一个循环中完成:
do {
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (Isnumber(ch)); // should probably be isdigit(ch)
答案 2 :(得分:0)
我用cin函数解决了它,如下所示,
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
//char ch;
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
getchar();
}
我删除了一个while循环。 并使用cin.fail和cin.good来避免使用IsNumber。它起作用了。