fputc在插入文本之前将第一行留空

fputc leaves the first line empty before inserting text

本文关键字:一行 插入文本 fputc      更新时间:2023-10-16

i使用getchar()和循环获取文本并使用fputc()将文本文件放入文本文件中,但是在编写后,它总是在文本文件中将第一行留为空。当字符输入为点(。)时,循环停止。如何删除第一行?

更新(2016年12月29日):我使用了devc ,并且代码在没有创建空白的情况下运行,但是我的VisualStudio2015有问题。

示例:创建一个名为test.txt

的文件

输入:这是文本。

输出:(在文本文件中)

[空白行]

这是文本

void writeFile(char *fileName){
    FILE *fp;
    fp = fopen(fileName, "wt"); //write text
    if (fp == NULL) {
        cout << "Failed to open" << endl;
        fclose(fp);
    }
    else {
        int i = 0;
        char c = '';        
        cout << "Enter a text and end with dot (.): ";
        fflush(stdin);
        //c = getchar();
        while (c != '.') {
            fputc(c, fp);
            c = getchar();
        }
        cout << "Written successfully" << endl;
        fclose(fp);
    }
}

出于好奇,是否有C函数的原因?在C 中进行类似的操作将更适合使用流,例如:

#include <iostream>
#include <fstream>
using namespace std;
void writeFile(const char *fileName)
{
    ofstream writeToFile;
    writeToFile.open(fileName);
    if (!writeToFile.is_open()) {
        cout << "Failed to open" << endl;
        return;
    } else {
        string stringToWrite{""};
        char c = '';        
        cout << "Enter a text and end with dot (.): ";
        while (c != '.') {
            std::cin >> c;
            stringToWrite += c;
        }
        writeToFile << stringToWrite << endl;
        cout << "Written successfully" << endl;
        writeToFile.close();
    }
}
int main()
{
    const char *fileName="test.txt";
    writeFile(fileName);
    return 0;
}

或,或者,

#include <iostream>
#include <fstream>
using namespace std;
void writeFile(const char *fileName)
{
    ofstream writeToFile;
    writeToFile.open(fileName);
    if (!writeToFile.is_open()) {
        cout << "Failed to open" << endl;
        return;
    } else {
        string stringToWrite{""};     
        cout << "Enter text and press return: ";
        getline(cin, stringToWrite);
        writeToFile << stringToWrite << endl;
        cout << "Written successfully" << endl;
        writeToFile.close();
    }
}
int main()
{
    const char *fileName="test.txt";
    writeFile(fileName);
    return 0;
}

c在第一个通过,因此是空白行。

将WARE循环更改为

  while( (c = getchar()) != EOF)
   {
       if(c == '.')
         break;
   }

看起来有些奇怪,但是对于从c。

中读取字符的惯用性