[英]Parse contents of array C++
我有此代碼:
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,而不是double值。
對?
這是我的完整代碼,可以隨意在dev或類似物中進行編譯,但請確保使用以下格式的文本文件:
String,Some String,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),但是我想首先解決這個值問題。
看起來sBuffer是一個字符串或一個字符數組,因此當您打印sBuffer [x]時,會將其視為字符而不是浮點數。
您需要將數字的字符串表示形式轉換為雙精度形式。 您可以使用C中的atof
或strtod
函數,也可以使用boost::lexical_cast<double>
。
看起來您的sBuffer[x]
不會包含雙sBuffer[x]
您將其與','
進行了比較。 那么sBuffer
是字符緩沖區嗎? 然后sBuffer[x]
只是“ 4.1415679”的一個字符,如果僅輸出此字符,setprecision將無法執行您想要的操作。
您可以使用stringstreams讀取字符串的雙精度型:
#include <sstream>
istringstream strm("4.1415679");
double d;
if (strm >> d) {
cout << "Your number: " << setprecision(2) << d << endl;
}
else {
cout << "Not a number." << endl;
}
如果您已經安裝了boost庫(總是一個好主意),則也可以使用boost::lexical_cast<double>("...")
,就像Matthew Crumley所說的那樣。
您可能想要std::fixed
:
cout << fixed << setprecision(2) << sBuffer[ x ];
// ^^^^^
如果sBuffer是一個char數組,則它不包含double。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.