如何让程序从.txt文件中识别和排序不同的变量类型?
How do I get my program to recognize and sort the different variable types from a .txt file?
对于c++(以及一般的编程)来说相当陌生。我正在尝试编写一个程序来读取以下输入。txt:
10
4
6
A 15 6
B 20 10
B 12 8
A 54 12
B 64 9
A 73 30
A 80 10
B 99 15
如图所示,有int变量和char (a和B)的组合。使用ifstream,程序完全可以识别前三个int(10,4,6)。然而,我正试图找出一种方法,它将剩余的变量分类到特定的数组中。
例如,我想让它认识到,每次有一个'A', 'A'之后的第一个int值进入一个数组,接下来的int值进入另一个数组。在这种情况下,我们将有数组[15,54,73,80]和[6,12,30,10]。
请注意input.txt没有设置,我需要能够让它读取具有不同数量的A和B的文件
有很多方法可以解决这个问题,包括编写boost::spirit语法,但我不会向刚接触c++的人推荐这种方法。
相反,我建议使用直接的方法,其中包括一个if语句:
- instead of streaming into an int, stream into a string.
- for each string (word), check if word is A or B, if so add to your char container. otherwise call stoi and add to your int container.
这里你写的例子相当快,所以可以有可以做得更好的部分,例如检查字符串是否是数字,或太多的向量使用etd .
#include <vector>
#include <memory>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <iterator>
#include <locale>
struct Data
{
std::string key;
std::vector< int > v;
};
bool isNumber( const std::string& s )
{
if( s.empty() )
{
return false;
}
std::locale loc;
std::string::const_iterator it = s.begin();
while( it != s.end() )
{
if( !std::isdigit( *it, loc) )
{
return false;
}
++it;
}
return true;
}
int main(int argc, char *argv[])
{
std::ifstream file;
file.open( "/home/rwadowski/file.txt" );
std::map< std::string, Data > map;
if( file.is_open() )
{
std::string line;
while( std::getline( file, line ) )
{
std::istringstream stream( line );
std::istream_iterator< std::string > it( stream );
std::istream_iterator< std::string > end;
std::vector< std::string > strings;
while( it != end )
{
strings.push_back( *it );
++it;
}
std::string key;
std::vector< int > v;
for( const std::string& s : strings )
{
if( isNumber( s ) )
{
v.push_back( std::stoi( s ) );
}
else
{
key = s;
}
}
Data data = map[ key ];
data.v.insert( data.v.end(), v.begin(), v.end() );
map[ key ] = data;
}
file.close();
}
std::map< std::string, Data >::iterator i = map.begin();
while( i != map.end() )
{
std::cout << "Key[" << i->first << "] = ";
for( int j = 0; j < i->second.v.size(); ++j )
{
std::cout << i->second.v[ j ] << " ";
}
std::cout << std::endl;
++i;
}
return 0;
}
使用此代码读取input.txt
(C++
)
std::ifstream file("input.txt");
if (!file.is_open()) {
cerr << "Errorn";
return 1;
}
int m, n, o, p, q;
char r;
std::vector<int> a, b;
std::vector<char> c;
file >> m >> n >> o;
while (file >> r >> p >> q) {
if (r == 'A') {
a.push_back(p);
b.push_back(q);
c.push_back(r);
}
}
file.close();
相关文章:
- 如何对不在数组中的变量进行排序?
- 按字母顺序对结构内数组变量中的名称进行排序
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- 如何对对象数组进行排序,而不考虑对象变量类型
- CUDD:提取变量排序
- 使用条件变量并联对向量的向量进行排序
- 对变量上的标准构造进行排序
- C 如何对数组变量进行排序
- 如何通过私有字符串变量按字母顺序对对象向量进行排序
- 根据类中的变量对类向量进行排序
- 如何制作一个集合,其中元素使用局部变量进行排序
- 排序变量C++
- std::map,自定义键类型,仅对一个变量进行排序
- 对其中一个变量的多变量结构进行排序
- 按结构内的变量对结构向量进行排序
- STL 按变量排序,然后按升序排序
- 全局排序和每原子变量排序有何不同
- std::vect使用成员变量排序
- 如何获取用户输入并按变量排序