Turbo C++ 程序卡住
Turbo C++ program getting stuck
程序本身工作正常,做它应该做的事情(将句子中的单词分开并打印出来)并且不会崩溃。但是,我无法退出程序。它只是卡住了。我什至尝试在最后给出一个 exit(0) 但它没有用。
你能告诉我哪里出了问题吗?
#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) = '[=10=]';
cout << "\n" << word;
if (end) break;
strcpy(s, s+i+1);
i = -1;
}
}
}
你告诉它这样做。删除 system("pause");
并且,请停止使用 C 库,并且 headers/tools 从 1980 年代开始。在此期间,我们已经离开了 MS DOS。如果你想要适销对路的技能,请学习实际的 ISO C++(它于 1998 年发明,从那时起近 20 年已经更新了 3 次)。
未定义的行为
你声明了一个指针但没有初始化它(你没有让它指向任何东西):
string s;
// a.k.a. char * s;
接下来,你输入进去:
gets(string);
这称为未定义行为:写入未知地址。一个好的操作系统和平台会出现段错误。
在计算机编程中,您需要使用数组分配内存:
char s[256];
或动态分配:
string s = new char[256];
在您从输入或其他地方输入值之前。
程序本身工作正常,做它应该做的事情(将句子中的单词分开并打印出来)并且不会崩溃。但是,我无法退出程序。它只是卡住了。我什至尝试在最后给出一个 exit(0) 但它没有用。
你能告诉我哪里出了问题吗?
#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) = '[=10=]';
cout << "\n" << word;
if (end) break;
strcpy(s, s+i+1);
i = -1;
}
}
}
你告诉它这样做。删除 system("pause");
并且,请停止使用 C 库,并且 headers/tools 从 1980 年代开始。在此期间,我们已经离开了 MS DOS。如果你想要适销对路的技能,请学习实际的 ISO C++(它于 1998 年发明,从那时起近 20 年已经更新了 3 次)。
未定义的行为
你声明了一个指针但没有初始化它(你没有让它指向任何东西):
string s;
// a.k.a. char * s;
接下来,你输入进去:
gets(string);
这称为未定义行为:写入未知地址。一个好的操作系统和平台会出现段错误。
在计算机编程中,您需要使用数组分配内存:
char s[256];
或动态分配:
string s = new char[256];
在您从输入或其他地方输入值之前。