简体   繁体   中英

Turbo C++ program getting stuck

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;
}
}

}

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM