3

ユーザーにコンソールで文字列を入力するように求めています。でも紐の長さはわかりません。

可変長の入力に適合する構造を定義するにはどうすればよいですか?

int main(){
    int i;
    char s[10];

    cout << "input string:";
    cin >> s;

    return 0;
}

サンプル コードでは、入力文字列の長さが 10 を超えるとヒープが破損します。

4

6 に答える 6

10

代わりにstd::stringを使用してください。例えば:

#include <string>

 std::string s;

 std::cout << "input string:";
 std::cin >> s;

または std::getline を使用して、行末文字までの行を取得します

std::getline(std::cin, s);
于 2013-05-28T07:19:31.590 に答える
3

C++ ではstd::string、特に可変長文字列の場合、char[] の代わりに使用する必要があります。

于 2013-05-28T07:20:08.277 に答える
0
#include <iostream>
#include <string>
using namespace std;

int main(){
    int i;
    string s;

    cout << "input string:";
    cin >> s;

    return 0;
}

char[] の代わりに std::string を使用します。

入力の後に char[] を使用する必要がある場合は、次の質問を参照できます。

std::string から char*

文字列を char* に変換します

例えば、

string s1;
cin >> s1;

char *s2;
s2 = new char[s1.length() + 1]; // Including \0
strcpy(s2, s1.c_str());

delete []s2;

new と delete がわからない場合は、malloc と free を使用できます。

于 2013-05-28T07:23:36.417 に答える