ユーザーにコンソールで文字列を入力するように求めています。でも紐の長さはわかりません。
可変長の入力に適合する構造を定義するにはどうすればよいですか?
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 <iostream>
#include <string>
using namespace std;
int main(){
int i;
string s;
cout << "input string:";
cin >> s;
return 0;
}
char[] の代わりに std::string を使用します。
入力の後に 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 を使用できます。