Вопрос

Doing a message program thing, and ran into a problem I don't understand with the buffer. The answer i'm sure is really simple but I just can't wrap my head around it. I'm trying to ask the user to type in a 10 digit name that will work as a username.

char myID[11]; // stores 10 characters plus newline at the end   
char sendBuff[1024] 

cout << "Enter your nickname(10 digits): ";  
cin >> myID;
cin.ignore(1000, '\n'); //clears buffer, or so I thought

Then I get some actual text for the message, store it in tempCharArray, then combine the username and the message text using sprintf_s.

char tempCharArray[1024];
cin.getline( tempCharArray, 1024 );                 

sprintf_s(sendBuff, 1024, "%s: %s", myID, tempCharArray );  //combines username and message text into one line before being printed

Now, my problem is that if I type in a name longer than 10 digits, it will print out the entire name in the sprintf_s function, despite myID being only 10 characters. I do not at all understand this behavior...

For example if I type in "HelloKitty69420" into myID, and then "yoyoyo" into tempCharArray, I would expect it to print "HelloKitty: yoyoyo" because myID can only hold 10 characters, yet it prints "HelloKitty69420: yoyoyo".

What's going on?

Это было полезно?

Решение

I would comment on your overall strategy for accomplishing your goal (ie. it is definitely no the way I would go about it) but I will focus on an answer.

Firstly, you should use std::cin.width(10) to limit the number of characters actually stored and moved to myID.

Secondly, you seem to have been lucky in the above case. The overflow bytes were written into the second array sendBuff and sprintf was writing characters from both myID and sendBuff.

The reason the overflow bytes were written into the second array is that the compiler simply placed myID and sendBuff in memory regions that were contiguous. ie myID[1000] would be the same as sendBuff[1000-11]

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top