at first glance this may look a dumb question but am really stuck and in a hurry.... I have a file that countain an X number of numbers stocked in a file. I can stock the numbers in the file in this way
22 56 102 9 302
in a single ligne with a space between each number.
Or i can stock them this way in one colone
22
56
102
9
302
either way i coudln't find an easy way to retrieve those number and stock them in a table to use them later on. Because one of the problem i don't know how many digit in each number (can be only one digit or even 5) so i can't use sscanf
.
So can anyone of you help me how to add those numbers to a table (whether the number in a single line or single colone, which ever easy). (in C language)
(really sorry if this question seems kinda dumb, but i'm really in a rush )
editt:: the number of numbers in the file han be really high
edit 2: this what i tried to do (in case the number are in a single colonne)
int i=0,k;
char buffer[500];
fd=fopen("Fdonne.txt", "r"); //fd global variable
fgets(buffer,300, fd);
while(feof(fd) == 0)
{
sscanf(buffer,"%d",tb[i]); //tb already declared also
i++;
fgets(buffer,300, fd);
}
for (k=0; k<(count+1); k++) // count is my X here
printf("%d ",tb[k]);
this seemed the most logical thing but, reading ligne by ligne and usse the sscanf but smh when i run the program nothing show (so there is a problem somewhere)
If I understand you right, you want to obtain the numbers which you can do with a help of string.Split
and Linq :
int[] numbers = File
.ReadLines(@"c:\MyFile.txt")
.SelectMany(line => line.Split(
new char[] { ' ', '\t', '\r', '\n' },
StringSplitOptions.RemoveEmptyEntries))
.Select(item => int.Parse(item))
.ToArray();
If tiy want to store the numbers in a file:
File
.WriteAllLines(@"c:\SomeOtherFile.txt", numbers);
TextFieldParser datReader = new TextFieldParser(Application.StartupPath + @"write here your file address");
datReader.SetDelimiters(new string[] { " " });
datReader.HasFieldsEnclosedInQuotes = true;
string colFields = datReader.ReadToEnd();
List<string> lineOrder = new List<string>();
using (StringReader sr = new StringReader(colFields))
{
string line;
while ((line = sr.ReadLine()) != null)
{
lineOrder.Add(line);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.