C++ 使用fscanf和fseek将第一个字母更改为大写
我的程序将.txt文件中每个单词的第一个字母改为大写。 我输入文件的地址。这个程序将一个单词保存为一个名为“word”的字符数组。它将数组的第一个单元格改为大写。然后计算该单词的字母,并移回该单词的第一个字母。然后它将新单词写入文件。 但是它不能正常工作C++ 使用fscanf和fseek将第一个字母更改为大写,c++,file,scanf,fseek,C++,File,Scanf,Fseek,我的程序将.txt文件中每个单词的第一个字母改为大写。 我输入文件的地址。这个程序将一个单词保存为一个名为“word”的字符数组。它将数组的第一个单元格改为大写。然后计算该单词的字母,并移回该单词的第一个字母。然后它将新单词写入文件。 但是它不能正常工作 #include <iostream> #include <stdio.h> using namespace std; int main () { int t=0, i=0,j=0; char word[
#include <iostream>
#include <stdio.h>
using namespace std;
int main ()
{
int t=0, i=0,j=0;
char word[5][20];
FILE *f;
char adres[20];
cin >> adres; // K:\\t.txt
f=fopen(adres,"r+");
{
t=ftell(f);
cout << t<<"\n";
fscanf(f,"%s",&word[i]);
word[i][0]-=32;
for (j=0;word[i][j]!=0;j++){}
fseek(f,-j,SEEK_CUR);
fprintf(f,"%s",word[i]);
t=ftell(f);
cout << t<<"\n";
}
i++;
{
fscanf(f,"%s",&word[i]);
word[i][0]-=32;
for (j=0;word[i][j]!=0;j++){}
fseek(f,-j,SEEK_CUR);
fprintf(f,"%s",word[i]);
t=ftell(f);
cout << t<<"\n";
}
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
int t=0,i=0,j=0;
字符字[5][20];
文件*f;
char-adres[20];
cin>>adres;//K:\\t.txt
f=fopen(adres,“r+”);
{
t=ftell(f);
这看起来像是家庭作业
- 不要尝试在同一个文件中读写。请使用不同的文件(例如,
in.txt
&out.txt
),您可以在末尾删除并重命名这些文件
使用C++流.
- 一次读一个字符
- 将算法分为三部分:
- 读写空格,直到找到非空格字符
- 将字符改为大写并写入
- 读写单词的其余部分
这是一个起点:
#include <fstream>
#include <locale>
int main()
{
using namespace std;
ifstream is( "d:\\temp\\in.txt" );
if ( !is )
return -1;
ofstream os( "d:\\temp\\out.txt" );
if ( !os )
return -2;
while ( is )
{
char c;
while ( is.get( c ) && isspace( c, locale() ) )
os.put( c );
is.putback( c );
// fill in the blanks
}
return 0;
}
我想,这就是你需要的
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
void readFile()
{
string word;
ifstream fin;
ofstream fout;
fin.open ("read.txt");
fout.open("write.txt");
if (!fin.is_open()) return;
while (fin >> word)
{
if(word[0]>='a' && word[0]<='z')
word[0]-=32;
fout<< word << ' ';
}
}
int main(){
readFile();
return 0;
}
#包括
#包括
#包括
使用名称空间std;
void readFile()
{
字符串字;
流鳍;
流式流量计;
fin.open(“read.txt”);
fout.open(“write.txt”);
如果(!fin.is_open())返回;
while(fin>>word)
{
if(单词[0]>='a'&&word[0]文件有多大?如果不是太大,我会将文件读入内存,然后在输出回时相应地修改它。\ifdef\uucplusplus
\error error compiler
\endif
为什么不使用std::fstream
?不是太大。但我们希望它也适用于大文件。你是不是在尝试请帮助我。谢谢,但是请看一下-ftell-函数。当我们不在单词上做任何活动而只是阅读单词时,-ftell返回的数字是不同的。我不明白为什么会不同-ZDF@user2583051我不知道你在说什么'您在问。如果您从流中读取,则流中的位置将被更新。如果当前位置为0,并且您使用getc
读取一个字符,则新位置将为1。如果您使用fscanf
,则位置将按读取的字符数递增。请参阅我的注释。@user2583051您使用的编译器是什么?谢谢,但我想找出我的程序有什么问题。如果可以的话,请帮助我。@mirmix为什么要写这样的字[i][j]!=0。写起来有点不对劲。
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
void readFile()
{
string word;
ifstream fin;
ofstream fout;
fin.open ("read.txt");
fout.open("write.txt");
if (!fin.is_open()) return;
while (fin >> word)
{
if(word[0]>='a' && word[0]<='z')
word[0]-=32;
fout<< word << ' ';
}
}
int main(){
readFile();
return 0;
}