How to get exclude null terminators when reading in a string?

吃可爱长大的小学妹 提交于 2019-12-25 03:12:04

问题


This program opens a file that contains a lake's name and its volume in units of hundreds of cubic miles--separated by a space. Its output is supposed to be the lake's name followed by a number of asterisks to represent its volume to the nearest hundred cubic mile (for example, a lake that has 12.7 hundred cubic miles in volume would print 13 asterisks). However, when it reads in a name that contains a space, it reads up until the space and then prints the next string in a new line. Is there any way I can read "gross dirty lake" as one line instead of "gross\ndirty\nlake" for example? Here's what I have so far:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void name_asterisks(char name[20], float vol);

main() {
       FILE *fp;
       fp = fopen("lakes.txt", "r");
       char name[20];
       float vol;
       if (fp == NULL) {
          printf("File does not exist.\n");
          system("pause");
          return 0;
       }
       while (fscanf(fp, "%s %f", name, &vol) != EOF) {
             name_asterisks(name, vol);
       }
       fclose(fp);
       system("pause");
}

void name_asterisks(char name[20], float vol) {
     int i;
     printf("%s", name);
     for (i = 0; i < (int)roundf(vol); i++)
         printf("*");
     printf("\n");
}

回答1:


"%s" is for scanning non-white-space. Code needs a different format specifier.

char buf[100];
while (fgets(buf, sizeof buf, fp) != NULL) {
   if (sscanf(buf, " %19[A-Za-z ]%f", name, &vol) != 2) {
     fprintf(stderr, "Unexpected data\n");
     break;
   }
   name_asterisks(name, vol);
 }

" ": Skip white-spaces.
"%19[A-Za-z ]": Scan and save up to 19 letters or spaces, append '\0'.
"%f": Skip white-spaces and save scan a float.

Note about original code: Better to check for what code wants than checking against 1 undesired result

// while (fscanf(fp, "%s %f", name, &vol) != EOF) {
while (fscanf(fp, "%s %f", name, &vol) == 2) {



回答2:


sample for like as gross dirty lake 12.7\n

#include <string.h>  //for strrchr
...
char line[64];//line buffer
...
while (fgets(line, sizeof line, fp)){
    char *p = strrchr(line, ' ');//search last ' '
    *p = '\0';
    //snprintf(name, sizeof(name), "%s", line);
    vol = atof(p+1);
    name_asterisks(line, vol);//name_asterisks(name, vol);
}


来源:https://stackoverflow.com/questions/30902337/how-to-get-exclude-null-terminators-when-reading-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!