My program changes first letter of each word to uppercase in a .txt file. I enter the address of file.this program save a word as a character array named "word".it changes the first cell of array to uppercase.then counts the letters of that word and and moves back to first letter of the word.then it writes the new word in file. But it dose not work correctly!!!
#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;
}
and the file is like:
hello kami how are you
the answer is that:
Hello kaAmihow are you
答案 0 :(得分:0)
这看起来像是家庭作业。
in.txt
&amp; out.txt
)。你可以删除&amp;最后重命名文件。这是一个起点:
#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;
}
<强> [编辑] 强> 你的程序有太多问题。
scanf
函数跳过字符串前面的空格。如果文件包含“abc”(注意'a'前面的空白区域)而你使用fscanf
,你会得到“abc” - 没有空格。toupper
函数。[编辑] 一个档案&amp; c风格:
#include <stdio.h>
#include <ctype.h>
int main()
{
FILE* f = fopen( "d:\\temp\\inout.txt", "r+b" );
if ( !f )
return -1;
while ( 1 )
{
int c;
//
while ( ( c = getc( f ) ) && isspace( c ) )
;
if ( c == EOF )
break;
//
fseek( f, -1, SEEK_CUR );
putc( toupper( c ), f );
fseek( f, ftell( f ), SEEK_SET ); // add this line if you're using visual c
//
while ( ( c = getc( f ) ) != EOF && !isspace( c ) )
;
if ( c == EOF )
break;
}
fclose( f );
return 0;
}
答案 1 :(得分: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;
}