gpt4 book ai didi

c++ - 解析字符串数组C++的内容

转载 作者:行者123 更新时间:2023-11-30 02:13:22 27 4
gpt4 key购买 nike

我读取了一个文件,并将其内容存储到一个字符串数组中。

我需要更改一些数值,由编译器解释为字符。

文件格式为:ABCDE,EFGHIJ KLMNOPQRS,45.58867,122.59750

我进行了搜索和研究,但还没有深入了解任何内容。

如果有人可以告诉我如何做到这一点,我将非常高兴。

而且我不允许使用 strtod;我认为这是一个 C 函数,我的程序只需要严格的 C++。

这是我到目前为止开发的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <sstream>


using namespace std;


int main()
{

string usrFileStr,
fileStr = "airNames.txt", // declaring an obj string literal
sBuffer,
sLine = "";

istringstream iStrStrm;

int lineCount = 1;
int nStart;


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() )
{
nStart = -1 ;
cout << "First Str " << 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 << " (Second Str: "; // lattitude loop


for ( int x = nStart + 1; x < sBuffer.length(); x++ )
{
if ( sBuffer[ x ] == ',' )
{
nStart = x;
break;
}
cout << sBuffer[ x ];
}

cout << ", Third String: ";
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 may close it

fgetc( stdin );
return 0;
}

我试过只读小数点后两位数,但我只读到一个字符。我的第一次尝试是使用 static_cast 但那还差得远。istringstream 变量不会让它的参数成为一个数组。我不知道该怎么办..

最佳答案

std::stringstream

学会爱它。不是 istringstream,因为您想从中获取输出。像这样的东西:

getline ( inFile, sBuffer );
stringstream myStream(sBuffer);
string first, second, third;
char comma;

myStream >> first;
myStream >> second;
myStream >> third;

float value1, value2;
myStream >> value1;
myStream >> value2;

此外,我建议您检查以确保文件确实打开了。

关于c++ - 解析字符串数组C++的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/472053/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com