CIN使用char类型阵列



我正在尝试使用char[]数组从std::cin读取字符。

这是一个简单的程序:

#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {    
    int age, years;
    char name[20];
    cout << "Enter your age in years: " << endl;
    cin >> years;
    cout << "Enter your name in years: " << name[15] << endl;
    age = years * 12;
    cout << " Your age in months is: " << age << endl;
    cout << "Your name is: " << name[15] << endl;
    return 0;
} 

以及我作为输出所得到的

Enter your age in years:
19
Enter your name in years:
 Your age in months is: 228
Your name is:

它不识别来自std::cin的数组。

有人可以帮忙吗?

#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main(){
    int age  , years ;
    char name[20];
    cout <<"Enter your age in years: "<< endl;
    cin >> years;
    cout <<"Enter your name in years: " <<endl;
    cin >> name;
    age = years*12;
    cout << " Your age in months is: " << age <<endl;
    cout << "Your name is: "<< name <<endl;
    return 0;
}

您的代码有两个区别:

cin << name;
(...)
cout << name << endl;

我假设您以为

cout&lt;&lt;"输入您的名字"&lt;&lt;名称[15]&lt;&lt;endl;

会让它要求输入。这不是cout所做的。Cout在控制台上打印出东西,它不要求输入。那是cin的任务。

您也不会在数组名称之后放置[15],这只会在数组中打印出第15个字符,只要输入的名称不达到15的长度,这就是垃圾字符。<</p>

int age, years;
char name[20];
cout << "Enter your age in years: " << endl;
cin >> years;
cout << "Enter your name in years: " << endl;
age = years * 12;
cin >> name;
cout << " Your age in months is: " << age << endl;
cout << "Your name is: " << name << endl;
cin.get();

最新更新