Hello! I wrote this small program that concatenates two strings with a space in the middle. It appeared to work fine at first and resembled something like the following:
This program takes two strings and displays them together with a space between them.
Please enter the first string: Hi!
Please enter the second string: Hello!
Hi! Hello!
Press any key to continue...
(exits).
Then I decided to test the 128 byte limit. I probably even passed the 260 character Array that I set up. I don't think it would matter because the cin only reads the first 128 bytes (char is usually worth about 1 byte), correct me if I am wrong and it does matter. When I tested the cin limit I did something that resembled this:
This program takes two strings and displays them together with a space between them.
Please enter the first string:nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn... //
and so on.
//
But then something strange happened. The second string, without me entering anything showed something such as:
Please enter the second string:nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
//
Then the program wouldn't perform what it was designed to do (display two strings with a space in the middle) and immediately displayed.
Press any key to continue...
(exits).
Can anbody explain what happened?
Thank you all for helping me in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
cout << "This program takes two strings that you enter in and displays them together with a space in between them.\n";
cout << "Please enter the first string:";
char szString1[260];
cin.getline(szString1, 128);
cout << "Please enter the second string:";
char szString2[260];
cin.getline(szString2, 128);
strncat(szString1," ", 260);
strncat(szString1, szString2, 260);
char * pszString1 = szString1;
while(*pszString1 != '\0')
{
cout << *pszString1;
pszString1++;
}
system("PAUSE");
return 0;
}
|