我需要知道如何知道在单词之间出现空格后何时停止存储文件中的字符串。在我打开文件并读取它后,例如:第一行是:427 671 +。我需要将“427”存储在 int 数组中,与变量中的“671”和“+”相同。
到目前为止,我已经弄清楚如何读取整行并打印它,但我遇到的问题是逐个字符读取并在按下空格之前将其存储。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <Laboratorio.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *datos;
FILE *resultados;
char bin[64]="",hex[16]="";
int oct[21];
ep = fopen ( argv[1], "r" );
if (ep==NULL) {
printf("Archivo vacio.");
return 0;
}else{
while (fgets(bin,64,ep)!=NULL){
printf("%s",bin);
}
fclose(ep);
}
}
最佳答案
最简单的方法是使用一个 char 变量并将每个字符一一存储到其中,如下所示:
while ((ch = getc(stream)) != EOF)
{
// do stuff with char
}
获得该字符后,您可以决定如何处理它,将其与 32(空格)进行比较以了解何时停止。
如果 char 是数字,您可以将其放入缓冲区中,直到到达空格为止,那么您所需要做的就是使用函数 atoi,该函数接收指向字符串的指针,并返回字符串的 int 表示形式。 例如:将字符串“432”转换为 int 432。
关于c - 当有空格时如何停止存储文件中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547033/