我有這樣的代碼:解析內容
cout << "Your Value is: ";
for (int x = nStart + 1; x < sBuffer.length(); x++)
{
if (sBuffer[ x ] == ',')
{
nStart = x;
break;
}
cout << sBuffer[ x ];
}
// setprecision doesnt work right when used with [] but i try anyway..
cout << setprecision(2) << sBuffer[ x ];
而我sBuffer [X]包含雙值,比方說,4.1415679
我想使用setprecision(2)僅顯示4.14
我卡住了,我該怎麼辦?
它不包含雙重因爲我正在閱讀一個文本文件,我忘記提到抱歉。
我的文本文件格式是:
字符串,一些字符串,49.59494,29.4094944
逗號進入sBuffer [X]之前存儲的每個字段。
所以我其實有一個雙。我認爲它不起作用的原因是編譯器將它解釋爲字符串或char,而不是雙重值。
對不對?
我的繼承人完整的代碼隨意在開發或東西編譯,但一定要使用文本文件格式:
字符串,一些字符串,54.2345,34.6654 ...
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
string usrFileStr,
fileStr = "test.txt", // declaring an obj string literal
sLine, // declaring a string obj
sBuffer;
int lineCount = 1;
fstream inFile; // declaring a fstream obj
// cout is the name of the output stream
cout << "Enter a file: ";
cin >> usrFileStr;
inFile.open(usrFileStr.c_str(), ios::in);
// at this point the file is open and we may parse the contents of it
while (getline (inFile, sBuffer) && !inFile.eof())
{
int nStart = -1 ;
cout << "First String " << lineCount << " (";
for (int x = nStart + 1; x < sBuffer.length(); x++)
{
if (sBuffer[ x ] == ',')
{
nStart = x;
break;
}
cout << sBuffer[ x ];
}
cout << ") ";
for (int x = nStart + 1; x < sBuffer.length(); x++)
{
if (sBuffer[ x ] == ',')
{
nStart = x;
break;
}
cout << sBuffer[ x ];
}
cout << " (First dValue";
for (int x = nStart + 1; x < sBuffer.length(); x++)
{
if (sBuffer[ x ] == ',')
{
nStart = x;
break;
}
cout << setprecision(2) << sBuffer[ x ];
}
cout << ", Second dValue: ";
for (int x = nStart + 1; x < sBuffer.length(); x++)
{
if (sBuffer[ x ] == ',')
{
nStart = x;
break;
}
cout << sBuffer[ x ];
}
cout << ") \n";
lineCount++;
}
cout << "There are a Total of: " << lineCount << " line(s) in the file."
<< endl;
inFile.clear(); // clear the file of any errors
inFile.close(); // at this point we are done with the file and we close it
fgetc(stdin);
return 0;
}
// use a funnction
是的,我知道我可以使用函數原型的循環過多(4) 但我想先解決這個值問題。