Возникли проблемы со строкой. Отладка требует «плохой указатель»

Я пишу программу, которая действует как преобразователь системы счисления и даже не добралась до забавной части математики и числовых значений, прежде чем облажаться.

В самом конце я объявил строку «value_array», и на ней есть надпись «bad ptr», когда я прохожу программу. Это мешает мне двигаться дальше.

#include <iostream>
#include <ctype.h>
#include <stdlib.h>
#include <string>

using namespace std;

int main()
{
//Initialization:
int base = 0;
int target = 0;
int i = 0;

//Won't exit until the user inputs a viable number for a base (between 1 and 16 inclusively).
for (i = 0; i < 1; i += 0)
{
cout << "Enter the base number system: ";
cin >> base;
cout << endl;

if (base>=2 && base<=16)
{
i++;
}

else
{
cout << "Invalid value. Please input a value between 1 and 16 inclusively." << endl;
}
}//Same as before but makes sure the target is a valid number.

for (i = 0; i < 1; i += 0)
{
cout << "Enter the target number system: ";
cin >> target;
cout << endl;

if (target>=2 && target<=16)
{
i++;
}

else
{
cout << "Invalid value. Please input a value between 1 and 16 inclusively." << endl;
}
}

string value_array = ""; //editted

cout << "Enter value in base (with no spaces): ";
cin >> value_array; //editted

//int k = basevalue(value_array,base);//Please disregard. Can't use this function until the strings are usable.

return 0;
}

1

Решение

Ты можешь использовать std::cin на value_array, но сначала удалите постоянство. Вы не можете изменить const string,

редактировать

Ты должен #include <string>,

1

Другие решения

Проблема, с которой вы сталкиваетесь, вызвана value_array, Вы объявили это const Это означает, что он не может быть изменен ничем (он доступен только для чтения) в течение срока его службы. Таким образом, когда вы пытаетесь присвоить ей строку, полученную из пользовательского ввода, компилятор сообщает вам, что это невозможно. Все отлично работает после удаления const ключевое слово.

Трудно сказать, какова точная причина плохой указатель ошибка, которую вы испытываете. В соответствии с этот ответ это может быть вызвано неправильным использованием необработанных указателей. Если вы используете их где-то после кода выше, убедитесь, что любой из них NULL, nullptr ни 0 когда используется.


Я немного изменил ваш код и добавил несколько комментариев, надеюсь, они будут полезны при разработке вашей программы:

#include <iostream>
#include <ctype.h>
#include <stdlib.h>

using namespace std;

int main()
{
//Initialization:
int base = 0;
int target = 0;

//PiotrSliwa: The loop can be removed with if-statement modified like below
cout << "Enter the base number system: ";
cin >> base;
cin.ignore(1024, '\n'); // PiotrSliwa: ignore up to 1024 characters or until newline is found in order to avoid bugs caused by more-than-required user input characters
cout << endl;

if (base<2 || base>16)
{
cout << "Invalid value. Please input a value between 1 and 16 inclusively." << endl;
return 0;
}

//PiotrSliwa: The loop can be removed with if-statement modified like below
cout << "Enter the target number system: ";
cin >> target;
cin.ignore(1024, '\n');
cout << endl;

if (target<2 && target>16)
{
cout << "Invalid value. Please input a value between 1 and 16 inclusively." << endl;
return 0;
}

string value_array = ""; //PiotrSliwa: removed 'const' from string which caused an error
cout << "Enter value in base (with no spaces): ";
cin >> value_array; //PiotrSliwa: The simplest method of obtaining user input and redirecting it to 'string' variable
cin.ignore(1024, '\n');

//int k = basevalue(value_array,base);//Please disregard. Can't use this function until the strings are usable.

return 0;
}

Живая демо


Кроме того, рассмотрите возможность включения функций в функции (или объекты), чтобы избежать дублирования кода, а также для обеспечения возможности повторного использования кода и улучшения читабельности. Например:

#include <iostream>
#include <ctype.h>
#include <stdlib.h>

using namespace std;

template<typename T>
T getUserInput(string message)
{
cout << message;
T input;
cin >> input;
cin.ignore(1024, '\n');
cout << endl;
return input;
}

bool isValidNumberSystem(int numberSystem)
{
return numberSystem>=2 && numberSystem<=16;
}

int main()
{
int base = getUserInput<int>("Enter the base number system: ");
if (!isValidNumberSystem(base))
{
cout << "Invalid value. Please input a value between 1 and 16 inclusively." << endl;
return 0;
}

int target = getUserInput<int>("Enter the target number system: ");
if (!isValidNumberSystem(target))
{
cout << "Invalid value. Please input a value between 1 and 16 inclusively." << endl;
return 0;
}

string value_array = getUserInput<string>("Enter value in base (with no spaces): ");

//int k = basevalue(value_array,base);//Please disregard. Can't use this function until the strings are usable.

return 0;
}

Живая демо

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector