[英]char array input limit?
如何使用 C++ 從控制台讀取 1000 個字符?
從對答案的評論更新:“我想要的是用戶可以輸入一個段落(比如 500 或 300 個字符)” - 即不總是 1000 個字符
使用以下代碼,我只能輸入一個限制(大約兩行)。 我究竟做錯了什么?
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
char cptr[1000];
cout<<"Enter :" ;
gets(cptr);
getch();
}
希望這可以幫助:
#include<iostream>
using namespace std;
int main()
{
const int size = 1000;
char str[size];
cout << "Enter: " ;
cin.read(str, size);
cout << str << endl;
}
使用getchar
在 for 循環中一次讀取一個字符,如下所示:
int i;
for (i = 0; i < 1000; i++){
cptr[i] = getchar();
}
編輯:如果你想早點打破循環,例如在換行符上,那么:
int i;
for (i = 0; i < 1000; i++){
char c = getChar();
if(c == '\n'){
break;//break the loop if new line char is entered
}
cptr[i] = c;
}
這可能是因為您正在閱讀新行。 當您遇到新行時, gets(char* ptr)
停止讀取,並將終止字符附加到字符串。
這是用戶可以輸入段落(1000、500 或 300 個字符)的解決方案。
代碼:
#include <iostream>
using namespace std;
int main()
{
char ch;
int count = 0;
int maxCharacters=0;
char words[1024]={' '};
cout<<"Enter maxCharacters 300,500,1000 >";
cin>>maxCharacters;
cout << "\nProceed to write chars, # to quit: \n";
cin.get(ch);
while( (ch != '#') )
{
cin.get(ch); // read next char on line
++count; // increment count
words[count]=ch;
cout <<words[count]; // print input
if (count>= maxCharacters) break;
}
cout << "\n\n---------------------------------\n";
cout << endl << count << " characters read\n";
cout << "\n---------------------------------\n";
for(int i=0;i<count;i++) cout <<words[i];
cout << "\n"<< count << " characters \n";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
輸出:
Enter maxCharacters 300,500,1000 >10
Proceed to write chars, # to quit:
The pearl is in the river
The pearl
---------------------------------
10 characters read
---------------------------------
The pearl
10 characters
Press any key to continue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.