fputc在插入文本之前将第一行留空
fputc leaves the first line empty before inserting text
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。
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 为什么插槽函数即使成功调用也无法插入文本
- fputc在插入文本之前将第一行留空
- 在Embarcadero Tools API中的光标位置插入文本
- 在文件中插入文本只工作一次
- C++ 在追加 Windows API 的特定位置插入文本
- 在QTextEdit中,如何检测用户何时只将光标插入文本区域一次
- 为什么 c++ 编译器在中间放置空格时不输出下一行的文本?
- 我怎么能读字符串和整数,在同一行从文本文件
- 在函数之间的c++代码中插入文本
- 如何在c++中从最后一行读取文本文件
- 说明:如何使用同一行打印文本后删除前一行-
- 每次一行显示文本文件,等待用户输入
- 使用std::ostream在每行之前插入文本
- VC++:在文本框中插入文本,不重复
- 插入文本