简体   繁体   中英

While Loop contines forever to get end of input string

How do I run the while loop until the end of line or null character reached.

Here is my code

#include<iostream>
using namespace std;
main()
{
    char input[20];
    cout<<"Enter a line: ";
    cin>>input;

    while(input!='\0')
    {
        cout<<"This is a text";

    }
    system("pause");
}

If you want to read until either a newline or a NUL, read one character at a time inside the loop.

#include<iostream>
int main()
{
  char input;
  std::cout << "Enter a line: " << std::flush;
  while(std::cin >> input && input != '\n' && input != 0) {
    std::cout << "This is a test\n";
  }
}

Notes:

  • main requires a return type
  • Never, ever, say "using namespace std;"
  • Don't forget to flush if you want cout to appear immediately.
  • Notice the compound test in the while condition:
    • First, did the read succeed?
    • Next, is it not '\\n' (one of your conditions).
    • Next, is it not NUL (the other of your conditions).
  • The body of the loop will be executed once per input character -- is that what you wanted?

But, consider if you have correctly specified your requirement. It is an unusual requirement -- why would there be a NUL in a text file, and why would you want to process each character individually?

In idiomatic C++, you can read the input file in a line at a time using std::getline :

std::string myString;
while(std::getline(std::cin, myString)) {
   // process myString
}

If you just want to read in a single line:

std::string myString;
if(std::getline(std::cin, myString)) {
  // process myString
}

Finally, if you want to read a line, and ignore its contents:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Like this:

std::string line;

if (std::getline(std::cin, line))
{
  std::cout << "Thank you, you said, \"" << line << "\".\n";
}
else
{
  // error, e.g. EOF
}

If you want to read multiple lines, use a while loop instead:

while (std::getline(std::cin, line))
{
  std::cout << "Thank you, you said, \"" << line << "\".\n";
}

try something like:

i = 0;
while ((input[i] != '\0') && i < 20)
{
  cout<<"This is a text";
  i++;
}

The issue is that you're reading an entire chunk of text at once and then printing it until the input is '\\0'. However, you're never actually updating this inside the loop. You can either use cin inside the loop to get the input, OR if you're trying to output each character, you can index the char array.

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