Copied program from textbook but getting these errors

 
implicit conversion changes signedness 'int' to 'size_type'(aka 'unsigned int')

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
  
//Demonstrates using a string object as ig it were an array.
#include<iostream>
#include<string>
using namespace std;

int main()
{
    string first_name, last_name;
    cout<<"Enter your first and last name:\n";
    cin >> first_name >> last_name;
    
    cout<< "Your last name is spelled:\n";
    int i;
    for(i = 0; i < last_name.length(); i++)
    {
        cout<< last_name[i] << " ";
        last_name[i] = '_';
}
    cout<< endl;
    for(i = 0; i < last_name.length(); i++)
       cout<< last_name[i] << " "; //Places a   
   // "_" under each letter.
    cout << endl;
cout << "Good day " << first_name << endl;
    return 0;
}
The program works fine for me, what you mention is a warning and not an error, try looking at your compiler's options to allow warnings.
> int i;
> for(i = 0; i < last_name.length(); i++)
Get a better text book.
It's been 20 years since this way of declaring a for loop was necessary in C++.

Try
for ( size_t i = 0; i < last_name.length(); i++)

Or
for ( string::size_type i = 0; i < last_name.length(); i++)

http://www.cplusplus.com/reference/string/string/
To continue Salem's train of thought, we also now have this kind of loop, which expresses the intent far better:

1
2
3
4
for (const auto& letter : last_name)
{
    cout<< letter << " "; 
}

The return type of std::string::size (or length) is size_t. size_t is an alias for one of the fundamental unsigned integer types.

std::string::[] expects a size_t value as as its position parameter.

https://en.cppreference.com/w/cpp/string/basic_string/operator_at

Mismatching the data type can be a warning, Visual Studio doesn't warn at default settings, unless you are compiling with the option warnings are treated as errors.

Your book is likely outdated, not using the latest features of the C++ standard. Creating the loop variable outside the for loops is not C++ style. It is something C would do.

What is your compiler? What is the publication date of your textbook?

salem c wrote:
Get a better text book.

That might not be an option, the textbook is probably required by the course/instructor. However outdated it looks to be.

I am using my cell phone at the moment since my laptop has been stolen. It uses Android. The IDE is calledCppriod
Topic archived. No new replies allowed.