iT邦幫忙

0

C問題

c

想請問我自己看課本輸入程式但後面為甚麼文字無法輸出阿!![https://ithelp.ithome.com.tw/upload/images/20210623/20138522AvvqO0wq0t.jpg]

#include<stdio.h>

#include<stdlib.h> 

#include <ctype.h>


int main(void)

{
	
	FILE *stream1;
	
	FILE *stream2;
	
	char string[10];
	
	stream1=fopen("olddata.txt","r");
	
	stream2=fopen("newdata.txt","w");
	
	if ((stream1 == NULL) || (stream2 == NULL)) 
	{
		
		printf("檔案開啟失敗\n");
		
		return 0;
		
	} 
	
		
	else 
	
	{
		
		while (fscanf(stream1,"%s",string)!=EOF)
		
		{
			
			string[0]=toupper(string[0]);
			
			fprintf(stream2,"%s",string);
			
		}
		
		fclose(stream1);
		
		fclose(stream2);
		
	}
	
	return 0;
} 
		
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2021-06-23 11:53:10

https://ithelp.ithome.com.tw/upload/images/20210623/2000178796sUzsXH5m.png

看起來
你的程式寫的是
1.讀 olddata.txt
2.將第一個字母大寫
3.寫到 newdata.txt

所以
你應該看 newdata.txt 的內容是否是預期的結果

p94060001 iT邦新手 5 級 ‧ 2021-06-23 11:54:31 檢舉

感謝你

p94060001 iT邦新手 5 級 ‧ 2021-06-23 14:15:19 檢舉

可是 我並沒有olddata的txt這樣應該要寫開啟失敗吧?

是這樣沒錯
https://ithelp.ithome.com.tw/upload/images/20210623/20001787dNdfBo9YZn.png

0
haward79
iT邦研究生 3 級 ‧ 2021-06-24 13:31:21

我測試可以成功執行的 code。

建議你用 printf() 印出讀到的東西來 debug,
不然就用 debug tool 來做 debug。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int main(void)
{

    FILE *stream1 = NULL;
    FILE *stream2 = NULL;
    char string[10];

    stream1 = fopen("olddata.txt", "r");
    stream2 = fopen("newdata.txt", "w");

    if((stream1 == NULL) || (stream2 == NULL))
    {
        printf("檔案開啟失敗\n");
    }
    else
    {
        while(fscanf(stream1, "%s", string) != EOF)
        {
            if(strlen(string) > 0)
                string[0] = toupper(string[0]);

            printf("%s\n", string);
            fprintf(stream2, "%s\n", string);
        }

        fclose(stream1);
        fclose(stream2);
    }

    return 0;
}

我要發表回答

立即登入回答