Task: It is necessary to search for a real number with a fixed point in the string. And implement it through an array of characters.

Below is an example of execution using string. Please help with such questions: How to declare a string in char? Find its length, given that the string is entered from the keyboard?

#include <iostream> #include <cmath> #include<conio.h> #include<string> using namespace std; int main(int args, double, char * argv[]) { setlocale(LC_ALL, "Russian"); int c, o, t, u, v, n = 0; int f = 0; int b = 0; int m = 0; o = 0; u = 0; t = 0; string sr; cout << "Введите строку" << endl; getline(cin, sr); for (int i = 0; i < sr.length(); i++) { if (sr[i] == '.') { if (!(isdigit(sr[i + 1])) || !(isdigit(sr[i - 1]))) { continue; } else { for (v = i - 1; v > 0; v--) { if (isdigit(sr[v])) { b = v; } else { if (sr[v] == '-') { b = v; break; } else break; } } for (f = b; f < sr.length(); f++) { if (sr[f] == '.') { break; } if (sr[f] == '-') { continue; } o++; } } f = 0; for (int n = i + 1; n < sr.length(); n++) { if (isdigit(sr[n])) { m = n; } else break; } for (f = m; f > 0; f--) { if (sr[f] == '.') { break; } u++; } } } if (o == u) { c = 0; } else { c = 1; } if (c == 0 && t == 0) { cout << "Число = "; for (int i = b; i <= m; i++) { cout << sr[i]; } } else { cout << "такого числа нет"; } cout << endl; system("pause"); return 0; } 
  • To begin with, you will have to allocate memory for the line, while if you cannot know the size of the line in advance, you will have to organize a loop with a check in which you have to concatenate strings when you enter a string with more buffer, well, you need to limit the number of characters size buffer - 1. Well, after the completion of reading, to find its length is no longer difficult. - Andrej Levkovitch

1 answer 1

It is clear that before declaring an array, you need to determine the size of the entered string. To do this, you need to allocate memory for a line with a large size, and then determine the size:

 char* p = new char[256]; std::cin.getline(p, 255); const size_t array_size = strlen(p); char array[array_size + 1]; strcpy(array, p); //если не нужно вводить еще одну строку, то delete p; 

And use array and its size array_size