Reputation: 15
The program itself works correctly, does what it's supposed to (seperate the words in a sentence and print them out) and does not crash. However, i cannot exit from the program. It just gets stuck. I even tried giving an exit(0) in the end but it didn't work.
Can you please tell me what's wrong?
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<process.h>
typedef char* string;
void main()
{
clrscr();
string s;
cout << "\nEnter something : ";
gets(s);
int i;
for (i = 0; i < strlen(s); ++i)
{
if ( s[i] != 32 )// && ( !isalnum(s[i-1]) || i == 0 ) )
{
char *word = s;
int end = 0;
for (; s[i] != 32 && i < strlen(s); ++i);
if (i == strlen(s)) end = 1;
else * (word + i) = '\0';
cout << "\n" << word;
if (end) break;
strcpy(s, s+i+1);
i = -1;
}
}
}
Upvotes: 0
Views: 1462
Reputation: 57678
Undefined Behavior
You declare a pointer and don't initialize it (you don't make it point to anything):
string s;
// a.k.a. char * s;
Next, you input into it:
gets(string);
This is known as undefined behavior: writing to an unknown address. A nice operating system and platform would segfault.
In computer programming, you need to allocate memory either by using an array:
char s[256];
or dynamic allocation:
string s = new char[256];
before you put values in, either from input or elsewhere.
Upvotes: 3
Reputation: 385098
You told it to do that. Remove system("pause");
And, please, stop using the C library, and headers/tools from the 1980s. We've moved on from MS DOS in the intervening time. If you want marketable skills, learn actual ISO C++ (which was invented in 1998, and has been updated three times in the nearly two decades since then).
Upvotes: 3