C/C++输入带空格的字符串方法
1. scanf("%[^\n]",str)
char str[100];
scanf("%[^\n]",str); //\n作为字符串输入的结束符
len = strlen(str); //获取str长度, 该方法在<cstring>头文件中
2. getline()
a. cin.getline(接收字符串: str, 最大接收字符个数: count - 1('\0'), 结束字符: 默认为‘\0’);
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[10];
cout << "Input: ";
// cin.getline(接收字符串: str, 最大接收字符个数: count, 结束字符: 默认为‘\0’);
cin.getline(str, 10);
cout << "Output: " << str << endl;
cout << "Length: " << strlen(str) << endl;
}
b. getline(cin, str)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Input: ";
getline(cin, str);
cout << "Output: " << str << endl;
cout << "Length:" << str.size() << endl;
}
3. cin.get(str, max_size - 1('\0'))
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100];
cout << "Input: ";
cin.get(str, 10);
cout << "Output: " << str << endl;
cout << "Length:" << strlen(str) << endl;
}
4. gets_s(str)
该方法已不被PAT编译器支持
a.cpp: In function ‘int main()’: a.cpp:10:17: error: ‘gets_s’ was not declared in this scope gets_s(input);
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char str[100];
cout << "Input: ";
gets_s(str);
cout << "Output: " << str << endl;
cout << "Length:" << strlen(str) << endl;
}