1-将字符串存在数组中的两种方法 2-如何在数组中使用字符串 3-cin只能读取一个单词,(读到换行符认为字符串结束) 4-介绍cin.get();cin.getline()
**1-将字符串存在数组中的两种方法:** int a[5]={'f','o','o','d','\0'};//'\0'用来标记字符串结尾 int a[5]="food";//称为字符串常量 **2-在数组中使用字符串** #include<iostream> #include<cstring>//c语言库;for the function 'strlen()'; 如果没有加上好像也没有报错 using namespace std; int main() { const int Size = 15; char name1[Size]="Judyhello"; char name2[Size]; cout<<"my name is "<<name1<<endl; cout<<" what's your name ?"<<endl; cin>>name2; cout<<"your name " <<name2<<" has "<<strlen(name2)<<" letters in an array of " <<sizeof(name2)<<"bytes"<<endl; //char 是一个字节 name1[4]='\0';//用来提前结束字符串 cout<<name1<<endl; return 0; **3-cin 只读取一个单词** 根据空格、制表符、换行符来确定字符串的结束 如: const int Size=20 int name1[Size]; int food[Size]; cout<<"what's your name ?"<<endl; cin>>name1;//输入 Judy kevin;由于有空格会当成是两个字符串 cout<<"what's your favorite food ? " cin>>food; cout<<name1<<" like eat "<<food <<endl; /*\\输出结果 what's your name ? Judy kevin what's your favorite food ? Judy like eat kevin*/ **4-cin 面向行的输入** 1)getline() cout<<"what's your name ? "<<endl; cin.getline(name1,Size);//输入 Judy kevin, cout<<"what's your farvorite food "<<endl; cin.getline(food,Size); cout<<name1<<" like eat "<<food<<endl; /*//输出结果 what's your name ? Judy Kevin what's your farvorite food? fish noodle Judy Kevin like eat fish noodle */ 2)get() /*cin.get(name1, Size);//输入 Judy kevin,然后输入换行符//这里cin.get()不会丢弃换行符 cout<<name1; cin.get(food, Size); //这条语句收到上行的换行符即认为结束 cout<<"your farovite food is "<< food<<endl; 输出结果: Judy Kevin your favorite food is */ 专门使用一个cin.get()来接收换行符或者使用cin.get().get() const int Size = 20; char name1[Size]; char food[Size]; cout << "what's your name ? " << endl; cin.get(name1, Size);//输入 Judy kevin, cin.get();//使用cin.get()的一个关键;用来读取换行符 cout << "what's your farvorite food " << endl; cin.get(food, Size); cout << name1 << " like eat " << food << endl; }cin.get()读取空行是什么意思?读取空行后输入将会被阻断,使用cin.clear()可以恢复输入
5-使用cin.get()遇到的问题 混合输入数字和字符串(其实依旧是换行符问题)
cout<<"what year was your house built?"<<endl; int year; cin>>year;//这里cin不会丢弃换行符 cout<<"what's is its address? "<<endl; char address[20]; cin.getline(address,20); cout<<"Year built:"<<endl; cout<<year; cout<<"Address:"<<endl; cout<<address; /*输出结果 what year was your house built? 1997 what's is its address? Year built: 1997 Address: */解决办法:
cin>>year; ... cin.get(); cin.getline(address,20); 或者 (cin>>year).get(); cin.getline(address,20);