知識點:函式,陣列、檔案綜合練習
創建用戶庫strpro.h和openfile.h,其中strpro.h中包含getString、sort和read函式,而openfile.h中包含openw函式。
在main函式中提示用戶輸入一句話,要求:
1. 呼叫getString函式將該英文句子讀入二維字符陣列,然后呼叫函式sort,利用選擇或冒泡演算法對上述句子中的單詞進行排序(按字母序)。
2. 將排好序的句子寫入到磁盤檔案data.txt中。要求打開data.txt檔案的操作須呼叫openw函式完成,打開時須檢查同名檔案是否存在,并提示用戶是否覆寫原檔案。
3. 呼叫函式read將data.txt中的內容讀回顯示到螢屏上
問題:冒泡有問題,閃退。
代碼如下:
#pragma once
#define LSIZE 81
char string[][LSIZE] = { 0 };
int getString();
void sort();
void read();
int i = 0,j = 0;
int getString()
{
char c;
while ((c = getchar()) != '\n')
{
if (c == ' ')
{
i++;
j = 0;
}
else
{
string[i][j] = c;
j++;
}
}
j = 0;
printf("%d\n", i);
return (i);
}
void sort()
{
char temString[LSIZE] = {0};
int a, b, c;
for (a=0;a<i;a++)
{
b = a;
for (c=a+1;c<i+1;c++)
{
if (strcmp(string[b], string[c]) > 0)
b = c;
if (b != a)
{
strcpy_s(temString, LSIZE, string[a]);
strcpy_s(string[a], LSIZE, string[b]);
strcpy_s(string[b], LSIZE, temString);
}
}
}
}
void read()
{
FILE* fp;
char str[LSIZE] = {'\0'};
fp = fopen("data.txt", "r");
while (fscanf(fp, "%s", str) != EOF)
puts(str);
fclose(fp);
}
uj5u.com熱心網友回復:
你這函式也沒有引數阿,不要引數的嘛?而且獲取字串你這個二維陣列也不是很理解,是要求二維?一維不是就可以了嘛?(看你存的是字符)emmmm太難了,留個樓窺屏學習一下大佬的uj5u.com熱心網友回復:
切出來的每個單詞后面需要加'\0'。改了改,供參考。
#include <stdio.h>
#include <string.h>
#define LEN 20 //每個單詞的最大長度
#define MAX 50 //一個句子的最大單詞數
//回傳單詞的個數
int getString(char str[][LEN]) {
int i = 0,j = 0;
char c;
while ((c = getchar()) != '\n'&&i<MAX) {
if (c == ' ') {
str[i][j]='\0';//每個單詞后面要加'\0'
i++;
j = 0;
} else
str[i][j++] = c;
}
return ++i;
}
//冒泡法排序
int sort(char str[][LEN],int len) {
char tmp[LEN];
int i,j;
for (i=0; i<len-1; i++) {
for (j=0; j<len-i-1; j++) {
if (strcmp(str[j],str[j+1]) > 0) {
strcpy(tmp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],tmp);
}
}
}
return 0;
}
void read() {
FILE* fp;
char str[LEN] = {'\0'};
fp = fopen("data.txt", "r");
while (fscanf(fp, "%s", str) != EOF)
printf("%s\n",str);
fclose(fp);
}
int openw(char str[][LEN],int len) {
FILE* fp;
char ch;
//測驗檔案是否存在
fp=fopen("data.txt","r");
if(fp) {
printf("檔案已存在,是否覆寫?(Y/N):");
scanf("%c",&ch);
if(ch!='Y') {
printf("不覆寫檔案。\n") ;
return 1;
}
}
fclose(fp);
//輸出
fp=fopen("data.txt","w");
int i=0;
while(i<len) {
fprintf(fp,"%s ",str[i]);
i++;
}
fclose(fp);
return 0;
}
int main() {
char str[MAX][LEN];
int i;
printf("請輸入一句話(英文):\n");
i=getString(str);
sort(str,i);
openw(str,i);
read();
}
uj5u.com熱心網友回復:
char str[MAX][LEN];
改為
char str[MAX][LEN] = { 0 };VS2015 C++環境除錯如下
uj5u.com熱心網友回復:
創建用戶資料庫怎么操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/242607.html
標籤:C++ 語言
上一篇:元音
下一篇:自動發郵件的腳本
