getline() get()
这两种都是可以接受一行字符串, get() 把换行符保留在输入列中
书上建议用get()
cin.clear() 清楚空行
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int Array_size = 20;
char input_name[Array_size] {};
char dessert[Array_size] {};
cout << "input a name \n";
cin.get(input_name, Array_size);
cin.get(); //这里也可以合并 cin.get(input_name, Array_size).get();
cout << "input dessert: " << endl;
cin.get(dessert, Array_size);
cout << "name: " << input_name << " like eat " << dessert << endl;
return (0);
}
这个只适用与char
strcpy(char, char) 复制
strcat(char1, char2) 添加
string 可以直接等于 或者 添加
#include <iostream>
#include <string>
#include <string>
#include <cstring>
using namespace std;
int main()
{
char charr1[20];
char charr2[20] = "jungle";
string str1;
string str2 = "this is string";
str1 = str2;
str1 = str1 + "dennis";
strcpy(charr1, charr2);
strcat(charr1, " hello");
cout << charr1 << endl;
cout << str2 << endl;
cout << str1 << endl;
return (0);
}
字符串长度
string : str1.size()
char : strlen(char1)
include <iostream>
#include <string>
#include <string>
#include <cstring>
using namespace std;
int main()
{
char charr[20];
string str1;
int a, b;
cin.getline(charr,20);
cout << "input is: " << charr << endl;
getline(cin, str1); //这里可以无限长
a = str1.size();
b = strlen(charr);
cout << "string is " << str1 << endl;
return (0);
}
char 没有赋值之前长度是随机的
string 初始化就定义长度为0
cout << R"(this could be the full sentecne without \n or other)" << endl; //这个可以直接忽视其他的特殊符号,打印引号中的内容