Convert String to Char in c and c++ 18

Опубликовано: 16 Июнь 2026
на канале: Arif Mahmood
295
0

Shows how to read from a file with string and #convert #string into #char in c plus plus and c.

c code:
#include<stdio.h>
int main()
{
FILE *input_file = fopen("test.txt", "r");
FILE *output_file = fopen("test.txt.out","w");//w for write a for append

char line[25];
for (int line_no = 1; fgets(line, sizeof(line), input_file) != NULL; ++line_no)
{
for (size_t i = 0; i < strlen(line); ++i)// stops where strings on a line finish
{

//printf("%c\n", line[i]);//
//fprintf(output_file, "%c\n",line[i]);
printf("%s\n", (char[sizeof(line)]) { line[i], 0 });
fprintf( output_file,"%s\n", (char[sizeof(line)]) { line[i], 0 });
}
//printf("%s", line);//
//fprintf(output_file, "%s", line);
}

if (input_file)
{
fclose(input_file);
fclose(output_file);
}
getch();
return 0;
}



c++ code:
#include <iostream> //for cout
#include <fstream> // for ofstream/ifstream
#include <string> //for << and getline
int main()
{
std::ifstream input_file("test.txt");
std::ofstream output_file("test.txt.out");

std::string line;
for (int line_no = 1; std::getline(input_file, line); ++line_no)
{
for (size_t i = 0; i < line.size(); i++)
{
//std::cout << line[i] << std::endl;
//output_file << line[i] << std::endl;
std::cout << std::string(1, line[i]) <<std::endl;
output_file << std::string(1, line[i]) << std::endl;
}
//std::cout << line << std::endl;
//output_file << line << std::endl;
}

if (input_file)
{
input_file.close();
output_file.close();
}

std::cin.get();
return 0;
}


#cplusplus #c #tutorial