从控制台获取字符串,但不知道长度

Get string from console but don't know the length

本文关键字:不知道 控制台 获取 字符串      更新时间:2023-10-16

我要求用户在控制台上输入一个字符串。但是我不知道字符串的长度

如何定义一个结构来适应可变长度的输入?

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