[英]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) = '\0';
cout << "\n" << word;
if (end) break;
strcpy(s, s+i+1);
i = -1;
}
}
}
你叫它這樣做。 刪除system("pause");
並且,請停止使用C庫和1980年代的標頭/工具。 在此期間,我們已經從MS DOS轉移了。 如果您想要適銷對路的技能,請學習實際的ISO C ++(該技術於1998年發明,從那時起近二十年來已進行了三次更新)。
未定義的行為
您聲明一個指針並且不對其進行初始化(您不使其指向任何東西):
string s;
// a.k.a. char * s;
接下來,您輸入:
gets(string);
這被稱為未定義行為:寫入未知地址。 一個好的操作系統和平台會出現段錯誤。
在計算機編程中,您需要使用數組來分配內存:
char s[256];
或動態分配:
string s = new char[256];
在從輸入或其他位置輸入值之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.