简体   繁体   English

从文本C ++中提取字符串数据

[英]Extracting string data from text C++

Im currently writing a c++ program that needs to extract string and numeric data from a text file. 我目前正在编写一个需要从文本文件中提取字符串和数字数据的c ++程序。 The format of the data is the following; 数据格式如下;

3225 C9+     ELECTR  C8      C        *      1.00E-6  -0.30       0.0

first entry is an integer, next 5 entries are strings and the last 3 are floats. 第一个条目是整数,接下来的5个条目是字符串,最后3个是浮点数。 No string is ever greater than 7 characters long. 没有字符串长度超过7个字符。

I am reading the file line by line and then extracting the data using; 我正在逐行读取文件,然后使用提取数据;

sscanf(ln.c_str(),"%d  %s  %s  %s  %s  %s  %e  %e  %e",
&rref[numre],&names[numre][0],&names[numre][1],&names[numre][2],&names[numre][3],
&names[numre][4],&nums[numre][0],&nums[numre][1],&nums[numre][2]);

this works fine untill I meet a line like; 这很好用,直到我遇到一条线;

  3098 SIC2H3+ ELECTR  SIC2H2  H        *      1.50E-7  -0.50       0.0

where one of the entrys is the full 7 characters long. 其中一个托盘是完整的7个字符长。 In this case I get; 在这种情况下,我得到;

names[3097][0] = "SIC2H3+ELECTR"

and, 和,

names[3097][1] = "ELECTR"

Anybody got any ideas...they will be much appreciated!! 任何人都有任何想法...他们将不胜感激!

The most likely problem is in the declaration of names : if you declared it as holding seven characters or less, and forgot to allocate space for terminating zero, you'd get the results that you are describing. 最可能的问题是在names声明中:如果你声明它持有7个字符或更少,并且忘记分配空间来终止零,你将获得你正在描述的结果。

char names[MAX][4][7]

will have enough space for strings of length 6 or less; 将有足够的空间用于长度为6或更短的字符串; for strings of length 7, you need 对于长度为7的字符串,您需要

char names[MAX][4][8]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM