【问题标题】:Retrieving Char digits from a text file and appending them into a String?从文本文件中检索 Char 数字并将它们附加到字符串中?
【发布时间】:2014-04-23 12:37:45
【问题描述】:

我正在尝试从文件中读取一些字符并将其转换为字符串。例如@2%4$$3。我的程序将从文本文件中取出243,现在我需要将它放在一个字符串中,以便我可以将其转换为 2043 并提供给INT var

任何帮助将不胜感激! :) 谢谢, 布赖恩

【问题讨论】:

  • 尝试与 + 连接并转换为字符串 _s+=_ch;然后转换为数字
  • 能否请您用您正在使用的语言标记您的问题?

标签: c++ string char var


【解决方案1】:

试试这个程序

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char file_buff[1024]="!@25#3$#4";
    char num_buff[1024];
    int len,i,k;
    // open file and read the entire contents specied as per the size
    FILE *f = fopen("file.txt", "r");
    fgets(file_buff, 1024, f);
    printf("String read: %s\n", file_buff);
    fclose(f);
    len=strlen(file_buff);
    // parse the buffer for digits and store it in a buffer
    for(i=0,k=0;i<len;i++)
    {
        if((file_buff[i] >= 0x30) && (file_buff[i] <= 0x39))
        {
            num_buff[k]=file_buff[i];
            k++;
        }
    }
    num_buff[k]='\0';
    printf("%s",num_buff);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 2014-08-05
    • 1970-01-01
    • 2022-01-21
    • 2014-04-15
    • 2023-01-11
    • 2011-12-27
    • 2018-03-12
    • 1970-01-01
    相关资源
    最近更新 更多