[英]C programming file operations reading the characters from the file and performing arithimitic operations on the numeric characters
我想編寫一個文件,從用戶輸入中輸入隨機字符,然后能夠讀取該文件並僅獲取數字字符並對這些數字字符執行算術運算,但是,在我創建文件並寫入文件后,我無法讀取文件並從中提取數據。 用戶輸入和輸出如下所示。
Please enter a string, no spaces: 1234567891234hgfns
the total number of integers is 0
the sum is: 0.00
This is the mean: nan
Program ended with exit code: 0
#include <stdio.h>
// defining a function to calculate and output the mean
float mean(float sum, float N)
{
float mean = sum/N;
printf("This is the mean: %.2f\n", mean);
return mean;
}
int main(void) {
// declaring the variables
char ch;
int N = 0;
float sum = 0;
// creating and opening a file
FILE *Fptr;
Fptr = fopen("File.txt","w");
// prompting the user to input string
printf("Please enter a string, no spaces: ");
// creating a loop to keep taking in characters until a blank space is detected
while( ch != ' ')
{
scanf("%c", &ch);
// writing to the file
fprintf(Fptr,"%c", ch);
}
fopen("File.txt","w");
//reading from the file and printing only numbers from the characters
while(fscanf(Fptr, "%c", &ch) != EOF)
{
// usign if statements
if( ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' ||
ch == '6' || ch == '7' || ch == '8' || ch == '9')
{
printf("%c\n", ch);
N++;
sum += (float)ch;
}
}
// printing the the total number of integers
printf("the total number of integers is %d\n", N);
printf("the sum is: %.2lf\n", sum);
// calling the function mean to calculate the mean
mean(sum, N);
return 0;
}
你的問題的根源是fopen("File.txt","w");
. 該調用將打開文件,但會刪除其中的所有數據。 如果要從文件中讀取,請使用“r”模式打開它。
先關閉文件,然后打開讀取。
Fptr = fopen("File.txt","w");
...
fclose(Fptr); // add
// fopen("File.txt","w");
Fptr = fopen("File.txt","r");
或者研究freopen()
。
或者在閱讀前打開讀寫"w+"
和rewind()
。
您的代碼中有許多問題需要解決。 與其逐一解釋,不如向您展示解決問題的替代方法。 但是,應該解決幾個值得注意的問題。 您不會關閉文件,因此在程序終止之前不會寫入任何數據。 這意味着當您嘗試閱讀它時,它無法被閱讀。 你用“w”模式打開文件; 如果文件中有任何數據,它將被截斷(丟棄)。 您丟棄fopen
返回的值,並且不能使用您丟棄的文件句柄。 嘗試:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
float
mean(float sum, float N)
{
float mean = sum/N;
printf("This is the mean: %.2f\n", mean);
return mean;
}
FILE *xfopen(const char *path, const char *mode);
int
main(void)
{
int ch;
int N = 0;
float sum = 0;
FILE *Fptr = xfopen("File.txt","w");
printf("Please enter a string, no spaces: ");
while( (ch = getchar()) != EOF && ch != ' ' ) {
fputc(ch, Fptr);
}
fclose(Fptr);
Fptr = xfopen("File.txt","r");
while( (ch = fgetc(Fptr)) != EOF ) {
if( isdigit(ch) ) {
putchar(ch);
N++;
sum += ch - '0';
}
}
printf("the total number of integers is %d\n", N);
printf("the sum is: %.2lf\n", sum);
mean(sum, N);
return 0;
}
FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = path[0] != '-' || path[1] != '\0' ? fopen(path, mode) :
*mode == 'r' ? stdin : stdout;
if( fp == NULL ) {
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.