Click here to Skip to main content
13,050,450 members (78,471 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I want to read some of the data from a txt file. For example:
This is content of "1.txt":

this is some data:
a = 1.25;
b = 5.34;
this is the other data:
c[0,0] = 7.684;
c[0,1] = 6.357;
c[0,2] = 1.325;

I want to read value of c[i,j] to array[k],
FILE *file;
file= fopen("1.txt","r");
while ( (sn = fscanf(file,"%*[^=] = %f",&znk) ) != EOF )
	if ( sn > 0 )
		array[i++] = znk;

But I can not get what I want in this way,because I also read the value of "a","b" into array[k], how should I change
fscanf(file,"%*[^=] = %f",&znk) 

Thank you very much !
Posted 31-Oct-12 4:12am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Try :
fscanf(file,"%*s %= %f",&znk);

Looking at the above we can break the pattern down into its parts as follows:

  1. %*s : this field should be ignored, as defined by the asterisk, and is a string field, as defined by the s.

  2. (space) : a blank space tells the scanner to ignore whitespace until the next non-blank character.

  3. %= : the next character is an equals sign and may be ignored.

  4. (space) : skip whitespace again.

  5. %f : the next field is treated as a floating point number.

Full details of the format types can be found here on MSDN[^].

Angela2012 31-Oct-12 20:35pm
Thank you very much , I tried this method , but it did not solve the problem, The value of "a" and "b" will be read into array[k] in your method. But I only want to read the data "c[i,j]=", that is the numbers following"]="
Richard MacCutchan 1-Nov-12 5:32am
Sorry but I do not understand what your problem is.
Angela2012 1-Nov-12 6:49am
I want to read the numbers after "] =", not numbers after " ="(for example: c[0,0] = 7.684 is the number I want, But a = 1.25 is not the number I want)
Richard MacCutchan 1-Nov-12 8:13am
This regex will work for both, but if you need to check for the prefix names then regex is probably not the best way to do it. Take a look at reading the entire string and then parsing the string to check for the text lines that you are interested in.
Angela2012 1-Nov-12 8:20am
Thank you very much, I solved the problem as you said, I read all the numbers and then selected the numbers I need.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 1 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100