Here's my problem:

The user needs to enter a char/string for a .dat file with a max of 15 characters. I've tried to use both a char and a string to make sure the user enters 15 or less characters. If I use char, and if the user inputs more than 15 characters, the program goes into a loop for the next cin. If I use string, I can't truncate the string to 15 characters, and I end up with an incorrectly formatted file because the full string gets written to the .dat file.

Needed solution:

I'd like to know how I can use either string or char to get the user to input 15 or less characters without having any overflows where the next cin goes into a seemingly infinite loop.

Recommended Answers

All 6 Replies

>'d like to know how I can use either string or char to get the user to input 15 or less characters
You can't portably do this. It requires a finer control of the input device than standard C++ supports. However, if you simply want to read lines and truncate the string to 15 characters if you read more than that, it's trivial to do:

#include <iostream>
#include <string>

using namespace std;

int main()
{
  const int max = 5;

  string s;

  // Read lines until the user gets tired
  while ( getline ( cin, s ) ) {
    // Trim the size to 15 if we read too many
    if ( s.size() > max )
      s.resize ( max );

    // Make sure it worked
    cout<< s <<'\n';
  }
}

Wow, thanx. The resize(x) function was all I needed to know about.

>The resize(x) function was all I needed to know about.
Somehow I doubt that.

Why is that?

>Why is that?
Because there are numerous ways to do the same thing. I just gave you one of them, which might not be appropriate for you. If it turns out to be too slow or take up too much space, then you need to know more, ne? :)

For my purposes it seems to serve me fine. Right now, optimizations are not important to my teacher.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.