从文件中读取字符串和整数

时间:2015-06-19 21:51:58

标签: c

我正在读取文本文件,其中某些行以星号开头,然后其他行包含指示矩形大小的数字。我对如何提取这些信息非常困惑。我最初尝试使用<%= form_for @assessment, :method=>"get", :url => url_for(:action => 'new') do |f| %> <%= f.select :patient_id, content_tag(:option,'select patient...',:value=>"")+content_tag(:option,'New Patient',:value=>"")+options_from_collection_for_select(@patients, 'id', 'full_name'), :class=>"form-control" %> <%= f.hidden_field :user_id, :value => current_user.id %> <div class="row" id="assessment-type" style="display:none;"> // WANT TO SET @patient HERE TO WHATEVER THE USER SELECTED IN ABOVE SELECT TAG // <% if @patient.has_past_assessments? %> <%= link_to "New Injury", templates_path, :id=>"new-injury", :remote=> true %> or <%= link_to "Followup Assessment", "#" %> <% end %> <%= f.hidden_field :template_id %> <% end %> </div> <script> $(function(){ $('#assessment_patient_id').chosen({width: "100%"}); }); $('#assessment_patient_id').change(function(){ var e = document.getElementById("assessment_patient_id"); var patient_id = (e.options[e.selectedIndex].value) if (patient_id == 0) { window.location.href = "/patients/new" } else { $('#assessment-type').slideDown(350); } $('#assessment-type').find('.template').on('click', function(){ startSpinner() var templateId = parseInt($(this).find('a').attr("id")); $('#assessment-type').find('.template').removeClass('active'); $(this).addClass('active'); $('#assessment_template_id').val(templateId); $('.new_assessment').submit(); }); }); </script> 来读取字符串,然后使用fgets()来读取整数,如图所示;

sscanf

但它打印得像这样;

*案例#1

高度:0,宽度:0

身高:10,宽度:20

...

*案例#2:形状

身高:10,宽度:20

身高:7,宽度:7

...

我应该逐个字符地阅读这个文件吗?

示例输入:(高度和宽度不会立即更新)

   while(fgets(line, MAX_CHARS, infile) != NULL) {
        if(line[0] == '*') {
            printf("%s\n", line);
        }
        sscanf(line, "%d%d", &height, &width);
        printf("height: %d, width: %d\n", height, width);
    }

1 个答案:

答案 0 :(得分:1)

您忘记在else之后添加if部分。

while(fgets(line, MAX_CHARS, infile) != NULL) {
    if(line[0] == '*') {
        printf("%s\n", line);
    }
    // Missing piece
    else {
       sscanf(line, "%d%d", &height, &width);
       printf("height: %d, width: %d\n", height, width);
    }
}