我是新来的,也是c ++的新手。
我刚开始上学的第一年,我接到了一项任务,其中一个问题是使用Char将八进制数转换为十进制数。
任务是创建一个程序,该程序接收来自用户的字符,并且预先不知道该数字的长度。用户应按'\t'
以开始计算十进制数。
我真的不明白它是如何工作的。因为如果我编写一个简单的算法,例如:
char ch;
cin<<ch;
cout>>ch>>endl;
我给它67
,它只打印6
。这意味着它分别读取每个字符,不是吗?
有人可以通过向我展示这个问题的算法或向我解释char是如何工作来帮助我理解它吗?
非常感谢 珊瑚
答案 0 :(得分:0)
您将获得有关如何通过char读取stdin char的足够信息。
请通过此链接。 http://www.cplusplus.com/forum/articles/6046/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input = "";
// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "You entered: " << input << endl << endl;
// How to get a number.
int myNumber = 0;
while (true) {
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
cout << "You entered: " << myNumber << endl << endl;
// How to get a single char.
char myChar = {0};
while (true) {
cout << "Please enter 1 char: ";
getline(cin, input);
if (input.length() == 1) {
myChar = input[0];
break;
}
cout << "Invalid character, please try again" << endl;
}
cout << "You entered: " << myChar << endl << endl;
cout << "All done. And without using the >> operator" << endl;
return 0;
}