char * [] 文本读取

请教一个问题:
char *name[]={"1","2"}
int Num ;

txt文件内容如下如下:
"1","2","3","4","5","6"

从文本文件读取这些数据,并读取到name中,并计数结果赋值到Num

利用本人珍藏字符串分解API,直接看代码:


//////////////////////////////////
#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <memory>
#include <vector>
#include <map>

using namespace std;

/* 字符串分割 API */
int split_s(const std::string& cont, std::vector<std::string>& result, char delim='\t') {
    std::size_t  new_tok = 0;
    std::size_t  cur_pos = 0;
    result.clear();

    for (; cur_pos < cont.size(); ++cur_pos) {
        if (cont[cur_pos] == delim) {
            std::string token = cont.substr(new_tok, (cur_pos - new_tok) );
            if (!token.empty()) {
                result.push_back(token);
            }
            new_tok = cur_pos + 1;
        }
    }

    // 处理结尾
    if (new_tok < cont.size()) {
        std::string token = cont.substr(new_tok);
        if (!token.empty()) {
            result.push_back(token);
        }
    }

    return  result.size();
}

int main(int argc, char* argv[]) {
    string  fn = "datafile.txt"; // 默认文件名
    if (argc > 1) {
        fn = string(argv[1]); // 通过参数传入文件名
    }
    std::ifstream datf(fn); // 默认文件名
    if (!datf) {
        std::cout << "Open file FAILED!" << endl;        
        return -1;
    }
    /* 对于小文件,可以考虑一次性读入内存 */
    std::string name((std::istreambuf_iterator<char>(datf)),
                     std::istreambuf_iterator<char>());
    datf.close();

    std::vector<std::string> result;
    int num = split_s(name, result, ',');

    /* 根据需要输出结果 */
    cout << "num :=" << num << endl;
    cout << "name :=" << name << endl;
    return 0;
}

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string name;
    int num = 0;
    ifstream infile("txt.txt");
    if (!infile) {
        cerr << "文件打开失败" << endl;        
        return 1;
    }
    while (getline(infile, name, ',')) {
        num++;
    }
    cout << "读取数量: " << num << endl;
    cout << "文件内容: " << endl;
    infile.clear();
    infile.seekg(0, ios::beg);
    while (getline(infile, name, ',')) {
        cout << name << endl;
    }
    infile.close();
    return 0;
}

该回答引用ChatGPT
下面是实现代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main() {
    char *name[] = {"1", "2"};
    int Num = 0;

    ifstream file("file.txt");
    string line;
    while (getline(file, line)) {
        istringstream ss(line);
        string word;
        while (getline(ss, word, ',')) {
            name[Num++] = new char[word.length() + 1];
            strcpy(name[Num - 1], word.c_str());
        }
    }
    file.close();

    for (int i = 0; i < Num; i++) {
        cout << name[i] << endl;
    }

    return 0;
}

为什么要用字符指针数组来保存结果?用字符指针数组存储从文件读取的数字,还需要创建字符数组来存储读取的每个数字。如果确实需要,是可以的。但感觉用int数组存储读取的数字感觉更简洁,所以下面的例子以这种办法来实现(Num定义为读取数据的项数,如果是累加读取数字的和也可以修改),代码如下:


#include <stdio.h>

int main(void){
    
    FILE * fp = fopen("0208.txt","r");
    if(fp==NULL){
        printf("文件打开失败!\n");
        return 0;
    }
    
    int result[10];
    int Num=0;
    char ch;
    while(feof(fp)==0){
        
        int read = fscanf(fp,"%d",&result[Num]);
        if(read==1){
            Num++;
        }else{
            fscanf(fp,"%c",&ch);    
        }
    } 
    
    printf("从文件读取的数字项数为: %d\n",Num); 
    if(Num>0){
        
        printf("从文件读取的数据为:\n");
        int j;
        for(j=0;j<Num;j++) {
            printf("%d ",result[j]);
        }
    }
    fclose(fp);

    return 0;
     
} 

0208.txt(测试文件内容):

"1","2""3","4""5","6",

img

根据您描述的问题,提供以下解题思路:
1.使用fopen来打开txt文件读取里面的数值数据
2.每读取到一个值就放入到name中
3.循环name,累加每个值到Num
4.printf输出Num的值

您可以使用以下代码读取文本文件并将数据存储到char *name数组中:

#include <stdio.h>
#include <stdlib.h>

#define MAX_LINE_LENGTH 100

int main(void) {
    char *name[100];
    int num = 0;
    FILE *fp;

    fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("Error opening file");
        return 1;
    }

    char line[MAX_LINE_LENGTH];
    while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
        char *token = strtok(line, ",");
        while (token != NULL) {
            name[num++] = strdup(token);
            token = strtok(NULL, ",");
        }
    }

    fclose(fp);

    num /= 2;
    printf("Num: %d\n", num);
    for (int i = 0; i < num; i++) {
        printf("name[%d]: %s, %s\n", i, name[2 * i], name[2 * i + 1]);
    }

    return 0;
}

该代码使用fopen打开文件,然后使用fgets读取每一行,并使用strtok函数将其分解为用逗号分隔的字符串。然后使用strdup复制字符串到name数组中。最后,关闭文件并打印结果。



#include <stdio.h>
#include <stdlib.h>

#define MAX_LINE_LENGTH 100

int main(int argc, char *argv[])
{
    char *name[100];
    int Num = 0;
    int i = 0;
    char line[MAX_LINE_LENGTH];
    FILE *fp = fopen("file.txt", "r");
    if (fp == NULL) {
        printf("Unable to open file\n");
        exit(1);
    }
    while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
        char *token = strtok(line, ",");
        while (token != NULL) {
            name[i++] = token;
            token = strtok(NULL, ",");
        }
    }
    Num = i / 2;
    fclose(fp);
    return 0;
}

说明:

将文件的内容读取到字符数组line中
使用strtok函数将字符串line分解为若干个以逗号为分隔符的字符串
将这些字符串存储到name数组中
Num的值是存储在name数组中的字符串的数量的一半,因为每个字符串都是一对,并且存储在数组的两个连续位置中。

用C语言的fscanf函数来读取这个文本文件。 代码: #include int main(){ char *name[] = {“1”, “2”}; int Num; FILE *fp; fp = fopen(“file.txt”, “r”); while (fscanf(fp, “%s", name[Num]) != EOF) { Num++; } fclose(fp); return 0; }

提供参考实例:C++读取文本文件到char*,链接:https://blog.csdn.net/ZxqSoftWare/article/details/100548007

供参考:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE* fp;
    int  i = 0, Num = 0;
    char* name[1024];
    fp = fopen("name.txt", "r");
    if (fp == NULL){
        printf("open file fail!\n");
        return 1;
    }
    while (1) {
        name[i] = (char*)malloc(sizeof(char) * 16);
        if (fscanf(fp, "%[^,],", name[i]) != 1) break;
        i++;
    }
    for (Num = i, i = 0; i < Num; i++)
        printf("%s ", name[i]);
    return 0;
}

img

可以通过使用fopen,fgets和sscanf等C语言中的文件处理函数来完成。

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

#define MAX_LEN 100

int main() {
    char *name[MAX_LEN];
    int Num = 0;
    char line[MAX_LEN];
    char str1[MAX_LEN];
    char str2[MAX_LEN];

    FILE *fp = fopen("file.txt", "r");
    if (!fp) {
        printf("Failed to open file.\n");
        return 1;
    }

    while (fgets(line, MAX_LEN, fp)) {
        if (sscanf(line, "\"%[^\"]\",\"%[^\"]\",", str1, str2) == 2) {
            name[Num] = (char *) malloc(strlen(str1) + 1);
            strcpy(name[Num], str1);
            ++Num;
            name[Num] = (char *) malloc(strlen(str2) + 1);
            strcpy(name[Num], str2);
            ++Num;
        }
    }

    fclose(fp);

    printf("Num = %d\n", Num);
    for (int i = 0; i < Num; ++i) {
        printf("name[%d] = %s\n", i, name[i]);
    }

    return 0;
}



以下是一个示例代码: 
#include<stdio.h> 
#include<stdlib.h>

#define MAXSTR 128

int main(void)
{
    char *name[MAXSTR];
    int Num = 0;

    FILE *fp;
    char buf[MAXSTR];

    //打开文件
    fp = fopen("./test.txt", "r");   
    if (fp == NULL)
    {
        printf("cannot open the file!\n");
        exit(0); 
    } 

    //从文件读出数据到name数组
    while (fgets(buf, MAXSTR, fp) != NULL)
    {
        name[Num++] = (char *)malloc(MAXSTR);
        sscanf(buf, "\"%[^\"]\",\"%[^\"]\"", name[Num-1], name[Num]);    
    }

     //关闭读取指针
    fclose(fp);

    return 0;
}

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

int main() { char name[2][20]; int Num; Num = 0; FILE *fp; fp = fopen("data.txt","r"); while(!feof(fp)) { fscanf(fp,""%[^"]","%[^"]"", name[Num], name[Num+1]); Num += 2; } fclose(fp); return 0; }

以下答案引用自GPT-3大模型,请合理使用:
文本读取函数用来从文件中读取文本内容。

函数原型:

char * [] readText(const char * filename);

filename:文件名

函数返回值:

char * []:读取的文本

函数功能:

读取文件中的文本内容,返回文本数组。

您可以使用C / C++中的string类来读取文件,然后使用string::split() 函数将字符串拆分为字符串数组,然后将该数组赋值给您所声明的char *name[]。同时,在拆分字符串时,您也可以计算出文件中字符串的总数,并将其赋值给Num变量

,题主,这个问题我来替你解决,若有帮助,还望采纳,点击回答右侧采纳即可。仅供参考:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string name;
    int num = 0;
    ifstream infile("txt.txt");
    if (!infile) {
        cerr << "文件打开失败" << endl;        
        return 1;
    }
    while (getline(infile, name, ',')) {
        num++;
    }
    cout << "读取数量: " << num << endl;
    cout << "文件内容: " << endl;
    infile.clear();
    infile.seekg(0, ios::beg);
    while (getline(infile, name, ',')) {
        cout << name << endl;
    }
    infile.close();
    return 0;
}

您可以使用C++的文件读取流来读取文件内容,并将其分割为若干行,然后逐行处理。下面是一个示例代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

int main() {
    // 存储读取的数据
    vector<vector<string>> data;
    // 定义文件读取流
    ifstream file("file.txt");
    // 判断文件是否存在
    if (!file.is_open()) {
        cout << "文件不存在" << endl;
        return 1;
    }
    // 读取文件内容
    string line;
    while (getline(file, line)) {
        vector<string> tokens;
        istringstream ss(line);
        string token;
        // 将每一行按","分割,存储到tokens中
        while (getline(ss, token, ',')) {
            tokens.push_back(token);
        }
        data.push_back(tokens);
    }
    // 关闭文件读取流
    file.close();
    // 计数结果并赋值到Num
    int Num = data.size();
    // 将读取的数据存储到name数组中
    char *name[Num][2];
    for (int i = 0; i < Num; i++) {
        name[i][0] = (char*)data[i][0].c_str();
        name[i][1] = (char*)data[i][1].c_str();
    }
    // 打印计数结果和读取的数据
    cout << "Num: " << Num << endl;
    for (int i = 0; i < Num; i++) {
        cout << name[i][0] << ", " << name[i][1] << endl;
    }
    return 0;
}


您可以使用下面的代码从文本文件读取数据并存储到数组中:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

const int MAX_NUM = 100; 

int main()
{
    char *name[MAX_NUM];   // 存储读取的数据
    int Num = 0;           // 记录读取的数据数量
    string line;           // 存储从文本文件中读取的一行数据
    ifstream file("data.txt");  // 打开文本文件

    // 如果文件打开失败,输出错误信息
    if (!file.is_open())
    {
        cout << "Failed to open file." << endl;
        return 0;
    }

    // 读取文本文件的每一行
    while (getline(file, line))
    {
        // 使用string流读取当前行的数据
        stringstream ss(line);
        string item;

        // 读取当前行的每个数据项
        while (getline(ss, item, ','))
        {
            name[Num] = new char[item.length() + 1];   // 为当前数据项分配内存
            strcpy(name[Num], item.c_str());           // 将数据项存储到数组中
            Num++;
        }
    }

    // 输出读取的数据
    for (int i = 0; i < Num; i++)
        cout << name[i] << endl;

    // 释放内存
    for (int i = 0; i < Num; i++)
        delete [] name[i];

    return 0;
}


在上面的代码中,我们使用了ifstream、stringstream和getline函数来读取文本文件中的数据。每次读取一行数据并使用stringstream读取当前行的每个数据项,最后将数据项存储到数组中,并记录读取的数据数量。