简体   繁体   English

Turbo C ++程序被卡住

[英]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. 我什至尝试最后给出一个exit(0),但是没有用。

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"); 删除system("pause");

And, please, stop using the C library, and headers/tools from the 1980s. 并且,请停止使用C库和1980年代的标头/工具。 We've moved on from MS DOS in the intervening time. 在此期间,我们已经从MS DOS转移了。 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). 如果您想要适销对路的技能,请学习实际的ISO C ++(该技术于1998年发明,从那时起近二十年来已进行了三次更新)。

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. 在从输入或其他位置输入值之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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