简体   繁体   中英

char array input limit?

How do I read in 1000 characters from the console using C++?

UPDATE from comment on answer: "What i want is that the user can input a paragraph ( say 500 or 300 characters)" - ie not always 1000 characters

With the following code, I am only able to input up to a limit( around two lines). What am I doing wrong?

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
    char cptr[1000];
    cout<<"Enter :" ;
    gets(cptr);
    getch();
}

Hope this helps:

#include<iostream>

using namespace std;

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

    cout << "Enter: " ;

    cin.read(str, size);

    cout << str << endl;
}

Use getchar to read one character at a time in for loop as below:

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

EDIT: If you want to break the loop early eg on new line char then:

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

This is likely due to the fact that you're reading a new line. gets(char* ptr) stops reading when you encounter a new line, and appends terminating character to the string.

Here is a solution to user can input a paragraph ( 1000, 500 or 300 characters).

code:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM