Hi
when I use code without if..else terminal window closes and "send error rapport" window pops up (WinXP). how can I limit the input to only 10 char without using if..else? I'm looking for some sort of flow control or stopping keyboard input.
thanks in advance
Here is my exercise code:
size_t StringLength(constchar *, const size_t);
int main()
{
}
size_t StringLength(constchar *String, const size_t MaxLen)
{
if(!String)
return(0);
size_t Len(0);
// Here, we'll iterate through the string until we
// encounter the null-character. Since the null--
// -character is zero, the loop will be false; thus
// terminating the loop.
while(*(String++))
{
// If the current amount of characters in the
// string is not equal to the maximum length,
// count it.
if((Len + 1) <= MaxLen)
++Len;
elsebreak;
}
return(Len + 1);
// The extra 1 is the null-character.
}
Since you cannot control the amount of characters entered by the user (your OS's API might yield something) with a console, you'll have to truncate the trailing characters by discarding them from the input buffer.
is very problematic. You make enough space for the user to enter 9 characters, and then have a trailing zero as C-strings must. You then get some input from you user, which you put into that array, and you then check that input to ensure it didn't overflow the buffer - but it's too late! You already put it into the buffer, so you will have already overflowed and trashed data.
For your example you probably want std::cin.getline()
1 2 3 4 5 6 7
char UserType[11]; // need one more than 10 for the end marker
std::cout << "Enter some char" << '\n';
std::cin.getline(UserType, 11); // limit input to 10
std::cout << UserType << '\n';
thank you guys. appreciate your help.
@Galik getline() solved the issue.
Currently I'm learning about Data types, Variables, Operators and sometimes searching around for reading codes to recognize what I learned.
I even learned to include C headers and run printf() instead of cout <<. I'm not sure why even should someone run C code inside C++ source.
@Moschops: True so I need to use cin first then extract 10 char of whole input and at last put them into my array. hope i got the logic correct.
@OsiumFramework thanks already copied & saved it. looks to advance for me. I don't know what const and * is. but I'm good student I'll learn it quick :)
---------------
But there is one more issue I couldn't understand why. when I use "cin" alone without "getline()" after hitting the space-bar, program doesn't save the rest of characters e.g " well, this is a test" print out only "well," part.
why it's happening?
and what is different between cin.getline() & cin.read()? all i know is getline sorts data in c-string and cin.read doesn't sort data in c-string. std::cin.getline(UserType, 11); and std::cin.read(UserType, 11); does the same job right?