char数组输入限制?

时间:2012-11-13 04:16:57

标签: c++ arrays 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();
}

4 个答案:

答案 0 :(得分:3)

希望这会有所帮助:

#include<iostream>

using namespace std;

int main()
{
    const int size = 1000;
    char str[size];

    cout << "Enter: " ;

    cin.read(str, size);

    cout << str << endl;
}

答案 1 :(得分:2)

使用getchar在for循环中一次读取一个字符,如下所示:

            int i;
            for (i = 0; i < 1000; i++){
              cptr[i] = getchar(); 
            }

编辑:如果你想提前打破循环,例如在新行char上:

            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; 
            }

答案 2 :(得分:1)

这可能是因为您正在阅读新行。遇到新行时gets(char* ptr)停止读取,并在字符串中附加终止字符。

答案 3 :(得分:0)

以下是用户可以输入段落(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