Reputation: 29
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)" - i.e. 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();
}
Upvotes: 1
Views: 4365
Reputation: 8587
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
Upvotes: 0
Reputation: 46
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;
}
Upvotes: 3
Reputation: 34367
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 e.g. 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;
}
Upvotes: 2
Reputation: 48086
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.
Upvotes: 1