簡體   English   中英

讀取從鍵盤讀取字符串並將它們寫入文件

[英]Reading reads strings from keyboard and writing them to a file

這是我的任務,您可以在下面找到我的具體問題和我編寫的代碼:

編寫一個讀取字符串並將它們寫入文件的程序。 字符串必須動態分配,字符串可以是任意長度。 讀取字符串后,將其寫入文件。 必須先寫字符串的長度,然后是冒號 (':'),然后是字符串。 當用戶在行上輸入一個點 ('.') 時,程序停止。

例如:

用戶輸入: This is a test程序寫入文件: 14:This is a test

題:

我的代碼添加了字符數和冒號,但沒有添加我輸入的字符串,以及輸入“.”時的字符串。 它不會退出

這是我到目前為止的代碼:

#pragma warning(disable: 4996)

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

#define MAX_NAME_SZ 256

int main() {

    char key[] = ".";

    char *text;
    int i;

    text = (char*)malloc(MAX_NAME_SZ);

    FILE* fp;

    do {
        printf("Enter text or '.' to exit: ", text);
        fgets(text, MAX_NAME_SZ, stdin);

        for (i = 0; text[i] != '\0'; ++i);

        printf("%d: %s", i);

        fp = fopen("EX13.txt", "w");

        while ((text = getchar()) != EOF) {
            putc(text, fp);
        }

        fclose(fp);
        printf("%s\n", text);


    } while (strncmp(key, text, 1) != 0);
    puts("Exit program");


    free(text);

    return 0;
} 

您的代碼中有很多問題,幾乎所有內容都是錯誤的。

只是幾個問題:

  • 你使用printf("%d: %s", i); 在屏幕上打印應該進入文件的內容。
  • while ((text = getchar()) != EOF)循環沒有任何意義。
  • 您在輸入第一行后關閉文件
  • 您忽略所有編譯器警告
  • 結束條件while (strncmp(key, text, 1) != 0)是錯誤的,你只有在字符串開始與測試. ,而您測試它為時已晚。

這可能是一個開始:

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

#define MAX_NAME_SZ 256

int main() {
  char* text;
  int i;

  text = (char*)malloc(MAX_NAME_SZ);

  FILE* fp;
  fp = fopen("EX13.txt", "w");
  if (fp == NULL)
  {
    printf("Can't open file\n");
    exit(1);
  }

  do {
    printf("Enter text or '.' to exit: ");
    fgets(text, MAX_NAME_SZ, stdin);

    if (strcmp(".\n", text) == 0)
      break;

    for (i = 0; text[i] != '\0' && text[i] != '\n'; ++i);

    fprintf(fp, "%d: %s", i, text);

  } while (1);

  fclose(fp);

  puts("Exit program");
  free(text);
  return 0;
}

但是有一個限制,在這個程序中,最大行長度是 254 個字符,不包括換行符。 據我了解,線長必須是任意的。

我讓你自己做這個練習,但在你的 C 知識水平上,這會很困難。

我認為這應該適用於短於 255 個字符的字符串。

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

#define MAX_NAME_SZ 256


int main()
{
     
     char key[] = ".\n";
     char *text;

     text = (char*)malloc(MAX_NAME_SZ);
     if (text == NULL)
     {
             perror("problem with allocating memory with malloc for *text");
             return 1;
     }

     FILE *fp;
     fp = fopen("EX13.txt", "w");
     if (fp == NULL)
     {
             perror("EX13.txt not opened.\n");
             return 1;
     }

     printf("Enter text or '.' to exit: ");
     while (fgets(text, MAX_NAME_SZ, stdin) && strcmp(key, text))
     {
             fprintf(fp, "%ld: %s", strlen(text) - 1, text);
             printf("Enter text or '.' to exit: ");
     }

     free((void *) text);
     fclose(fp);

     puts("Exit program");

     return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM