Tried an explicit conversion failed:

if ((int)temps[i] < min && (int)temps[i]>0) { min = (int)temps[i]; } 

The task itself: Write a program that prints a temperature close to 0, among the input data. If two numbers are equally close to zero, a positive integer should be considered closer to zero (for example, if the temperature is -5 and 5, output 5). Do not change the type of input data. Here is the actual code itself:

 #include <iostream> #include <string> #include <cstdlib> using namespace std; void min_temp(int n, string temps) { int min = 5526; int min1 = -273; for (int i = 0; i < temps.size(); i++) { if ((int)temps[i] < min && (int)temps[i]>0) { min = (int)temps[i]; } else if ((int)temps[i] < min1 && (int)temps[i] < 0) { min1 = (int)temps[i]; } } if (min > abs(min1)) { cout << min1<<endl; } else cout << min<<endl; } int main() { int n; // the number of temperatures to analyse cin >> n; string temps; for (int i = 0; i <= n; i++) { getline(cin, temps); } min_temp(n, temps); system("pause"); return 0; } 

1 answer 1

Nothing in the description of your job indicates that you should use objects of type std::string .

As for your code, it is meaningless. For example, in this cycle

 for (int i = 0; i <= n; i++) { getline(cin, temps); } 

which has n + 1 iterations, with each iteration you rewrite the value of the temps object. Therefore, in temps after the loop is executed, there will always be the value that you entered during the last iteration of the loop.

The program can be written easier. In the cycle, integer values ​​are entered and each value entered is compared with the current minimum temperature value.

If you need to use a string, the string must contain integer values ​​separated by spaces. Then you can use the std::istringstream class to split the string into integers and compare them.

Regarding your question in the title without regard to what you wrote in the question itself,

I do not know how to convert the type of string to int

then in C ++ there is a standard stoi function that performs this conversion.

  • string is definitely needed) But with the loop I did not understand, but how then to fill the n-th number of values? - SecDet
  • @SecDet Why is this std :: string necessary? From the description of your task it does not follow at all. - Vlad from Moscow
  • I’m not entering the values, but the program, then it drives the code itself through the tests. Let's say this according to the charter of the string value :) - SecDet
  • @SecDet See my updated answer. - Vlad from Moscow
  • Well, what about the cycle. How to fill? In the cycle, cin? - SecDet