简体   繁体   English

将N位数字的连续行读入整数数组,每个数字位于单个数组位置

[英]Reading consecutive lines of N digit number into an integer array with each digit in a single array position

My file has a 9 digit number in each line and I want to extract each number line-wise and try storing it in a integer array with each digit in each array position. 我的文件每行都有一个9位数字,我想逐行提取每个数字,然后尝试将其存储在一个整数数组中,每个数字都位于每个数组位置。

I tried, 我试过了,

while((fgets ( sequence, 9, loose ) != NULL)) {
    if((sequence[0]-'0')==1)
        count(sequence[1]-'0');
    else
        break;
}

copying each line to a array called sequence and then converting it to number by sequence[0]-'0' , but it doesn't seem to work right; 将每行复制到一个名为sequence的数组,然后按sequence[0]-'0'将其转换为数字,但这似乎行不通; it returns some random number value and loses the file descriptor of my required file. 它返回一些随机数值,并丢失我所需文件的文件描述符。

My file looks something like this 123456789 123456798 123456879 123456897 123456978 我的文件看起来像这样123456789 123456798 123456879 123456897 123456978

i just want first line to be stored as sequence[0]=1,sequence[1]=2,... then the next line text to be over written on sequence[] and so on until end of file 我只希望将第一行存储为sequence [0] = 1,sequence [1] = 2,...,然后将下一行文本覆盖在sequence []上,依此类推,直到文件结束

If I understand your problem correctly, I'd suggest that you accept each line of input as a string to a two dimensional character array. 如果我没有理解你的问题,我建议你接受输入的每一行作为一个字符串转换为二维字符数组。 That way you get each number in its own row with each of the digits in the columns. 这样,您就可以在自己的行中获得每个数字,并在列中获得每个数字。 I can give you the code if you need, but this is pretty straightforward. 如果需要,我可以给您代码,但这很简单。

Note - You can convert the characters back to integers for further manipulation 注意-您可以将字符转换回整数以进行进一步操作

EDIT - Added code 编辑-添加代码

with open('/root/text.txt') as f:
    number = f.readlines()
number = [x.strip('\n') for x in number]
print number

The number printed is a list. 打印的号码是一个列表。

number[0] will give you the first number in your file (123456789) 数字[0]将为您提供文件中的第一个数字(123456789)

number[0][0] will give you 1. 数字[0] [0]会给你1。

int(number[0]) can give you the integer 123456...as opposed to the corresponding string. int(number [0])可以给您整数123456 ...,而不是对应的字符串。

Edit 2 - oops. 编辑2-哎呀。 Just realized I gave you python code :-\\ 刚意识到我给了你python代码:-\\

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

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