我有这样的代码:解析内容
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) 但我想先解决这个值问题。