1

如何使用 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

4 回答 4

3

希望这可以帮助:

#include<iostream>

using namespace std;

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

    cout << "Enter: " ;

    cin.read(str, size);

    cout << str << endl;
}
于 2012-11-13T05:34:56.633 回答
2

用于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; 
            }
于 2012-11-13T04:22:47.783 回答
1

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

于 2012-11-13T04:20:31.330 回答
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
于 2012-11-13T08:24:06.927 回答