重複の可能性:
スペース文字を含む入力から文字列を読み取りますか?
文字列(技術的には文字配列)を入力として受け取る際に問題に直面しています。次の宣言があるとします。
char* s;
「Enter」を押すまで、このcharポインターを使用して文字列を入力する必要があります。助けてください! 事前にサンクス。
重複の可能性:
スペース文字を含む入力から文字列を読み取りますか?
文字列(技術的には文字配列)を入力として受け取る際に問題に直面しています。次の宣言があるとします。
char* s;
「Enter」を押すまで、このcharポインターを使用して文字列を入力する必要があります。助けてください! 事前にサンクス。
C と C++ の両方fgets
で、新しい行まで文字列を読み取る関数を使用できます。例えば
char *s=malloc(sizeof(char)*MAX_LEN);
fgets(s, MAX_LEN, stdin);
あなたが望むことをします(Cで)。C++ では、コードは似ています
char *s=new char[MAX_LEN];
fgets(s, MAX_LEN, stdin);
C++std::string
は、文字の動的シーケンスであるクラスもサポートしています。文字列ライブラリの詳細: http://www.cplusplus.com/reference/string/string/ . 文字列を使用する場合は、次のように記述して行全体を読み取ることができます。
std::string s;
std::getline(std::cin, s);
場所: プロシージャは、ヘッダーまたは C++ で見つけることfgets
ができ<string.h>
ます<cstring>
。この関数は、C 用、およびC++ 用malloc
で見つけることができます。最後に、関数を含むクラスがファイルで見つかります。<stdlib.h>
<cstdlib>
std::string
std::getline
<string>
アドバイス (C++ の場合): C スタイルの文字列と のどちらを使用するかわからない場合はstd::string
、私の経験から、文字列クラスの方がはるかに使いやすく、より多くのユーティリティを提供し、はるかに高速であることをお伝えします。 C スタイルの文字列よりも。これはC++ 入門書の一部です:
As is happens, on average, the string class implementation executes considerably
faster than the C-style string functions. The relative average execution times on
our more than five-year-old PC are as follows:
user 0.4 # string class
user 2.55 # C-style strings
最初に、メモリを割り当てる必要があるこの文字列に入力を取得します。その後、gets または fgets または scanf を使用できます
C++ について考える場合は、cin.getline()
役に立つかもしれません。
cin>>variable_name; を使用できます。入力にスペースがない場合。スペースを含む入力の場合、c++ で gets(variable_name) を使用します
塗りつぶしを開始するs
前に割り当てる必要があります
1)入力文字列のサイズが事前にわからない場合は、使用できますrealloc
char* s = calloc(1,sizeof(char));
char t;
int len;
while(scanf("%c", &t)==1)
{
if(t== '\n')
break;
len = strlen(s);
s= realloc(s,len+1);
*(s+len) = t;
*(s+len+1) = '\0';
}
2)入力文字列の最大長が事前にわかっている場合は、次の方法で scanf を使用して文字列を char の配列に直接読み取ることができます。
char s[256] // Let's assume that the max length of your input string is 256
scanf("%[^\r\n]",s) // this will read your input characters till you heat enter even if your string contains spaces
うーん、OPが述べているので:
「Enter」を押すまで、このcharポインターを使用して文字列を入力する必要があります
これを試してみようと思ったのですが、頭の中で、これは動的バッファーであり、ポインターを使用malloc
および使用しています。realloc
ただし、バグが含まれている可能性がありますが、要点はそこにあります。ニッピッキーはさておき...
コードがひどい場合は申し訳ありません... ::)
char *ptr = NULL, *temp_ptr = NULL;
int c = 0, chcount = 0, enter_pressed = 0;
do{
c = fgetc(stdin);
if (c != '\n' || c != -1){
chcount++;
if (ptr == NULL){
ptr = malloc(sizeof(char) + chcount + 1);
if (ptr != NULL) ptr[chcount] = c;
else printf("ABORT!\n");
}else{
temp_ptr = realloc(ptr, chcount + 1);
if (temp_ptr != NULL){
ptr = temp_ptr;
ptr[chcount] = c;
}else{
// OK! Out of memory issue, how is that handled?
break;
}
}
}else{
enter_pressed = 1;
}
}while (!enter_pressed);
ptr[chcount] = '\0'; // nul terminate it!