Reading multiple data types from .txt in C

Click For Summary
SUMMARY

The discussion centers on reading multiple data types from a .txt file in C, specifically extracting x, y, z coordinates and a chemical symbol from a space-delimited format. The user seeks to convert these values into appropriate data types: doubles for coordinates and a string for the atom symbol. The solution was achieved using the fscanf() function, which effectively parses the input file into the desired variables. This method allows for efficient reading and type conversion in a single operation.

PREREQUISITES
  • Understanding of C programming language
  • Familiarity with file I/O operations in C
  • Knowledge of data types in C, specifically doubles and strings
  • Experience with parsing strings and formatted input functions
NEXT STEPS
  • Explore the fscanf() function in C for formatted input
  • Learn about error handling in file operations in C
  • Research string manipulation techniques in C for further data processing
  • Investigate alternative methods for reading files, such as getline() and sscanf()
USEFUL FOR

This discussion is beneficial for C programmers, particularly those working with scientific data processing, file I/O, and anyone needing to parse structured text files into different data types.

Sdakouls
Messages
8
Reaction score
0
Hi,

I'm wondering if anyone would be able to help me with the following problem:

I have an input file in the form (values delimited by spaces):

0.0 0.0 0.0 Ga
0.5 0.5 0.5 As
1.0 1.0 1.0 In
.
.
.

and so on. (Basically it's a .txt containing x, y and z coordinates of atoms in a crystal lattice, along with the chemical symbol for the atom at a given lattice site.)

My aim is to try and write a program that would allow me to (for a given line of the file) to extract the data from this file so that I'd end up with (for line 2 in the above, for example):

x = 0.5
y = 0.5
z = 0.5
atom = As

where, x, y and z are doubles and atom is char* (or a string... I'm not fussy).

I'm familiar with the usual "reading an entire line of a file into a string" approach, but I'm not sure how to proceed in this instance since I need to take different parts of the line as different datatypes.

I've tried googling the problem and reading around, but I couldn't find anything hugely relevant.

Any help would be greatly appreciated.
 
Technology news on Phys.org
fscanf()
 
Problem solved by a helpful officemate.

Mods: Delete thread.
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
5K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
10
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 19 ·
Replies
19
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
3
Views
4K