从控制台获取字符串,但不知道长度
Get string from console but don't know the length
我要求用户在控制台上输入一个字符串。但是我不知道字符串的长度。
如何定义一个结构来适应可变长度的输入?
int main(){
int i;
char s[10];
cout << "input string:";
cin >> s;
return 0;
}
如果输入字符串长度超过10,则示例代码将导致堆损坏。
请改用std::string。例如:
#include <string>
std::string s;
std::cout << "input string:";
std::cin >> s;
或者使用std::getline获取一行直到结束字符
std::getline(std::cin, s);
在c++中,应该使用std::string
而不是char[],尤其是对于可变长度的字符串。
这是一个有效的、通用的示例,允许您读取包含空白的字符串:
#include <string>
#include <iostream>
int main()
{
std::string s;
std::cout << "Type a stringn";
std::getline(std::cin, s);
std::cout << "You just typed "" << s << ""n";
}
cplusplus.com表示,输入流中字符串的>>运算符使用空格作为分隔符。因此,如果您需要字符串能够包含空格,则必须使用std::getline(...)
(wich与istream::getline(…(不同!!!(
基本上是这样的:
std::string inputString;
std::getline(cin, inputString);
我的答案受到这个答案的启发
#include <iostream>
#include <string>
using namespace std;
int main(){
int i;
string s;
cout << "input string:";
cin >> s;
return 0;
}
使用std::string而不是char[]。
如果您需要在输入后使用char[],可以参考以下问题:
std::字符串到字符*
将字符串转换为字符*
例如,
string s1;
cin >> s1;
char *s2;
s2 = new char[s1.length() + 1]; // Including
strcpy(s2, s1.c_str());
delete []s2;
如果你不知道new和delete,你可以使用malloc和free。
基本上,建议您始终使用std::string来获得可变长度的输入。如果您需要将输入存储在数组中以将其传递给函数或其他东西,则仍然如此。你可以这么做。虽然它很蹩脚。
/* #include <string> */
std::string s;
std::cout<<"Enter the String";
std::getline(std::cin, s);
char *a=new char[s.size()+1];
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
std::cout<<a;
问候
Genocide_Hoax
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 叮当不知道PTRDIFF_MAX?
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 我不知道这条线是做什么的
- 如何在不知道C++中有多少可选参数的情况下在循环中使用va_arg?
- 在不知道套接字的情况下关闭网络连接
- 如果我不知道每个列表中有多少个数字,我如何将给定数量的数字列表作为输入?
- 我不知道导致错误的原因 (C3074)
- 我不知道为什么这段代码会让核心被转储?
- 我正在尝试制作一个自平衡机器人,但编译时存在错误。我不知道如何解决它
- 循环通过网格获取温度,但不知道如何告诉程序停止循环
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 反转字符串.不知道为什么这个逻辑是错误的.C++
- 将 clangd stderr 重定向到文件而不是控制台
- 从控制台获取字符串,但不知道长度