Two problem with String in C

Hello,
First of all, I want to ignore the Enter and get the name from the input.
Second why the below syntax doesn't work? I have to use strcopy.
ch_arr_result[z] = ch_arr_first[i];


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
	char ch_arr_first[4][10];
	int int_arr_first[4];

	char ch_arr_second[4][10];
	int int_arr_second[4];


	char ch_arr_result[4][10];
	int int_arr_result[4];

	int z = 0;

	for (int i = 0; i < 2; i++)
	{
		printf_s("Team %d : ", i);
		//scanf_s("%c", &ch_arr_first[i]);
		fgets(ch_arr_first[i],5, stdin);

		printf_s("Result %d : ", i);
		scanf_s("%d", &int_arr_first[i]);

		printf_s("Team %d : ", i);
		fgets(ch_arr_second[i], 5, stdin);

		printf_s("Result %d : ", i);
		scanf_s("%d", &int_arr_second[i]);

		if (int_arr_first[i] > int_arr_second[i])

		{
			int_arr_result[z] = int_arr_first[i];
			strcpy_s(ch_arr_result[z] , ch_arr_first[i]);
		//	ch_arr_result[z] = ch_arr_first[i];
			z++;
		}
		else
		{
			int_arr_result[z] = int_arr_second[i];
			strcpy_s(ch_arr_result[z], ch_arr_second[i]);
			z++;
		}


	}

	for (int i = 0; i < z; i++)
	{
		printf_s("Team %s : ", ch_arr_result[i]);

		printf_s("Result %d : ", int_arr_result[i]);
		printf_s("\n");
	}

}

you don't have any strings.
a string looks like this

string s;
string a;
s = "hello world";
a = s;

you are using what we call C-strings, which is what the C language uses but c++ allows them (c++ allows over 95% of C even when its not the best way to do code).

c++ does not allow you to copy arrays with an equals sign. you can do that with vectors, but not arrays. This is why it didn't work: a C-string is just an array.

<cstdio> is the c++ header, you are using the C header.
printf, scanf, etc are also C. where are you getting this stuff? Your book or examples or something are teaching you C, or worse, 1980s era style C++ which is C with a couple of additions.

If you are actually TRYING to learn and write C, then
#include <string>
using namespace std;
those are c++ and have to go. Its ok to learn C, and we can even help some, but say so up front if that is a goal.
Last edited on
Dear Jonnin,

Thank you very much for your answer.
You are right and I should write in the C language, not C++.
When you want to use C string library functions #include <string.h> in C code. Use #include <cstring> when writing C++ code when using the C string library functions.

The C string library function strcpy_s requires your compiler to be able to use the C11 (or later?) standard.

https://en.cppreference.com/w/c/string/byte/strcpy
Topic archived. No new replies allowed.