Search code examples
c++stringiostream

How to store input as a string until one or more specific string(s) has/have been entered in C++?


this is my first entry in the site and currently I am student at university and learning C++. In a given homework, I encountered a problem and have been trying to solve it but could not find a full solution. In short, I need to take input until the word "END" or "end" is read. For example;

Enter source string: there are good times
and there are bad times
END
Enter search string: are+

...and goes on

The problem is that I use cin.getline() function (as I will be showing later), but I can't control for both of "END" and "end" at the same time. cin.getline() function just checks for one.

Here is a piece of my code;

#define MAX_TARGET_LENGTH 500
char target[MAX_TARGET_LENGTH];
cout << "Enter source string: ";
cin.getline (target, MAX_TARGET_LENGTH, 'END');

As you see, I need to make it check for "END" or "end", whichever comes first.

Is there any way or any other function which makes it run as it should be?

Thanks for your attention and if my typing of the problem is confusing or wrong in some way, sorry.


Solution

  • I came up with the following solution:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    #define MAX_TARGET_LENGTH 500
    
    int main() {
      char target[MAX_TARGET_LENGTH];
      while(true)
      {
        cout << "Enter source string: ";
        while(true)
        {
          cin.getline (target, MAX_TARGET_LENGTH);
          std::string line = target;
          if(line.compare("end") == 0 || line.compare("END") == 0)
          {
            break;
          }    
        }
      }
      return 0;
    }
    

    I am using the String class to solve the problem.

    Strings are objects that represent sequences of characters.

    and they come with useful features. One of those is the function "compare". With it you can check if a string is equal to another string. The function will return 0, if the strings are identical. Otherwise it will return 1 or -1 (more information here).

    The main thing going down in in the inner while loop.

    while(true)
    

    lets the while loop continuing forever.

    You get a new line of input with

        cin.getline (target, MAX_TARGET_LENGTH);
    

    which you store in the variable target. You can then turn "target" into a string with

    std::string line = target;
    

    because, the types are compatible. The if-statement then checks the input for "end" or "END".

    if(line.compare("end") == 0 || line.compare("END") == 0)
    {
      break;
    }    
    

    If one or both of those statements are true, "break" exits the inner while loop and makes the program print "Enter source string: " again.