c++输入字符串的方法有哪些
在C++中,输入字符串的方法有以下几种:
- 使用cin:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
return 0;
}
- 使用getline:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << "You entered: " << str << endl;
return 0;
}
- 使用scanf:
#include <cstdio>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
return 0;
}
- 使用fgets:
#include <cstdio>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("You entered: %s\n", str);
return 0;
}
版权声明
本文仅代表作者观点,不代表博信信息网立场。
上一篇:Redis中的Pipeline是什么 下一篇:如何使用PHP代码创建文件夹