您正在存儲字符代碼,而不是整數。如果在標準輸入上鍵入1
並將其存儲在char
中,將存儲的是1
的ASCII碼,而不是整數值1
。
因此,如果您分配給b[i]
,你應該做的:
b[i] = a[i] - '0'; // Of course, this will make sense only as long
// as you provide digits in input.
而且,這樣做:
cout << b;
將打印b
數組的地址,而不是它的內容。此外,在這裏使用strlen()
並不是一個好主意,因爲您的數組a
不是空終止的。
讓一旁如何類型不安全的,這是,這裏的因素是什麼,你可能打算做的事:
#include <iostream>
#include <cstring>
using std::cout;
int main()
{
char a[3] = { 0, 0, 0 };
gets(a);
int b[3];
for(unsigned int i = 0; i < std::min(strlen(a), 3u); i++)
{
b[i] = a[i] - '0';
// ^^^^^
cout << b[i];
}
}
這裏是你會怎麼做上面的C++ 11:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string a;
getline(std::cin, a);
std::vector<int> b;
for (char c : a) { if (std::isdigit(c)) b.push_back(c - '0'); }
for (int x : b) { std::cout << x << " "; }
}
這裏是上述功能的修改應該針對C++ 03以及工作:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string a;
getline(std::cin, a);
std::vector<int> b;
for (std::string::iterator i = a.begin(); i != a.end(); i++)
{
if (std::isdigit(*i)) b.push_back(*i - '0');
}
for (std::vector<int>::iterator i = b.begin(); i != b.end(); i++)
{
std::cout << *i << " ";
}
}
的Visual Studio Express是一個免費的downl爲善的緣故誰還會使用Turbo C++?這顯然迫使你編寫C代碼而不是C++代碼。它不支持'fgets'嗎? –