文字列でファイル文字列を読み込むと、>>演算は最初の文字列を取得しますが、 "i"で始まります。最初の文字列が "street"であると仮定すると、 "istreet"のようになります。ファイルからC++を読み込むと、3つの奇妙な文字が入ります
他の文字列は大丈夫です。私は別のtxtファイルを試しました。結果は同じです。最初の文字列は "i"で始まります。何が問題ですか?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int cube(int x){ return (x*x*x);}
int main(){
int maxChar;
int lineLength=0;
int cost=0;
cout<<"Enter the max char per line... : ";
cin>>maxChar;
cout<<endl<<"Max char per line is : "<<maxChar<<endl;
fstream inFile("bla.txt",ios::in);
if (!inFile) {
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
while(!inFile.eof()) {
string word;
inFile >> word;
cout<<word<<endl;
cout<<word.length()<<endl;
if(word.length()+lineLength<=maxChar){
lineLength +=(word.length()+1);
}
else {
cost+=cube(maxChar-(lineLength-1));
lineLength=(word.length()+1);
}
}
}
を*脇*:**ループ条件として '.eofを()'は絶対に使用しないでください。あなたのケースでそうであるように、ほとんど常にバグのコードを生成します。ループ条件で入力操作を行うことをお勧めします。 while(inFile >> word){...} 'となります。 –