C++ range based loops - How do they work? [duplicate] - c++

This question already has answers here:
How does the range-based for work for plain arrays?
(6 answers)
C++11 range based loop: How does it really work
(3 answers)
Closed 2 years ago.
I'll preface this question by saying I am knowledgeable on C, and I'm learning C++.
Suppose I've got an std::string object and I want to go thru all of its characters to verify it (for example, only 4 letters allowed).
I have seen for (type var : array) being used in some code around a week ago, but I couldn't remember how it was used. I'm wondering.. exactly how does this work, and why does it work? Logically it shouldn't.
AFAIK, arrays don't really "know" what their length is. So suppose I have this code:
int arr[] = { 1, 2, 3 };
for (int item : arr) {
std::cout << item << std::endl;
}
How the hell does the for loop know when to stop? Arrays are simply put allocated memory (stack, in this case) that start from a specific address and go on. There's no "stored length" (AFAIK) for arrays. This is why it is a programmer's responsibility to store the length of the array, and do for (int i = 0; i < [length]; i++) but this somehow works?
Would love some explanation. Specific use case for my code:
std::string test = "Hello World!";
for (char letter : test) {
if (letter == 'l') {
std::cout << "'l' exists!" << std::endl;
} // result should be 3 prints.
}

Related

content of a vector appears to be empty but a value is assigned to it (C++) [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
uint8_t can't be printed with cout
(8 answers)
Closed 1 year ago.
this is probably a really basic C++ question but I'm very new to C++ so your patience and help is appreciated.
I'm not quite sure why the following code is unable to print out the content of the matrix. I should mention that the variable K is the integer 3.
std::vector<uint8_t> enc_matrix;
for(size_t i = 0; i != K; ++i) {
enc_matrix[i*(K+1)] = 1;
cout << "enc_matrix: " << enc_matrix[i*(K+1)] << endl;
// cout << enc_matrix.at(i*(K+1)) //doesn't show anything either
cout << "i: " << i*(K+1) << endl;
}
For whatever reason nothing gets printed for enc_matrix[i*(K+1)] but the result of i*(K+1) does get printed. Below is what gets printed:
enc_matrx:
i: 0
enc_matrx:
i: 4
enc_matrx:
i: 8
I'm not sure if it has anything to do with the type of the matrix so I've included the additional info below:
typeid(enc_matrix[0]).name() => h and
typeid(enc_matrix).name() => St6vectorIhSaIhEE
Why is it that enc_matrix doesn't get printed? I am expecting to see 1 assigned to it when i equals to 0, 4 and 8. Thank you.

c++: How do you print to stdout a casted int value? [duplicate]

This question already has answers here:
How to output a character as an integer through cout?
(6 answers)
Convert an int to ASCII character
(11 answers)
Closed 3 years ago.
I have a program that takes a string. Using the check() function that calculate the sum of all the value in the string of integers, I make additional computations, aka ss. The issue comes when I try to convert ss, which is an int, into a char, c.
When I try to print out the newly converted value, nothing prints out on the console, not even an error message.
I have tried using static_cast<char>(ss), and it won't work. Yet when I try to print out the ss value, I get it to print it out.
Source Code
void sum(string input)
{
int s = check(input);
int ss = (s * 9) % 10;
char c = ss;
cout << "val is: " << c << endl;
}
int main()
{
string x = "7992739871";
sum(x);
return 0;
}
Can someone explain what I might be doing wrong and how it can be fixed?
You can use std::to_string() (C++11) but making sure that the value of c is something that can be printable is a better practice.

Concatenating string and int in c++ [duplicate]

This question already has answers here:
Why in the code "456"+1, output is "56" [duplicate]
(3 answers)
Closed 6 years ago.
I am doing some exercises in C++ when I came upon something not so clear for me:
cout << "String" + 1 << endl;
outputs : tring
I suggest it is something with pointer arithmetic, but does that mean that everytime I print something in quotes that is not part of previous defined array,I actually create a char array ?
A quoted string (formally a string literal) is an array of const char, regardless of whether your printing it or doing anything else with it.
Code:
cout << "String" + 1 << endl;
has the same effect as this:
const char *ptr = "String";
cout << ptr + 1 << endl;
so no you do not create a new array, you just change pointer and pass it to std::cout

How can I seperate a string into individual characters in c++? [duplicate]

This question already has answers here:
For every character in string
(10 answers)
Closed 8 years ago.
As the title says, how can I seperate a string into individual characters in c++? For example, if the string is "cat" how can I separate that into the characters c,a, and t?
Thanks
By using the operator[]. e.g.
std::string cat{"cat"};
if(cat[0] == 'c')
//stuff
If you're using std::string you can simply use .c_str( ) that will give you an array of the chars.
In c++11 you could also do:
for( auto c : a )
{
cout << c << '\n';
}
http://ideone.com/UAyxTo
If you want to store them in a vector:
string str("cat");
vector<char> chars(str.begin(), str.end());
for (char c : chars)
cout << c << endl;

How to create Character based arrays in Turbo C++?

I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this :
char x[7][7] = {"sec","min","hr","day","week","month","year"};
And when I try to fetch the data from it like this :
for (i=0;i<=7;i++){
cout << x[i] << "\n";
}
I get some strange results! Like this :
Can anyone tell me where I'm going totally wrong! And please I'm new to C++ so can you provide me a good explanation.
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify your for loop as for (i=0;i < 7;i++). (< instead of <=.)
You're going over the end of the array, which may give you garbage data or may just crash your program.
for (i=0;i<=7;i++){
cout << x[i] << "\n";
}
The array indices will only range from 0 to 6, and you check for i<=7. Change that to i < 7.
The problem is not in creating the array but in printing the results. Arrays in C, C++, Java, C#... and many other languages are 0 based. When you declare an array of 7 elements you iterate from 0 to 6:
for ( int i = 0; i < 7; ++i ) {
std::cout << x[i] << std::endl;
}
Note: < and not a <=.