繁体   English   中英

字符数组输入限制?

[英]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.

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