This is a program convert a string to ASCII. Example: string is «hi», the output is 104105. But the progam displays the number 104 then displays the number 105. So, how can I save the number «104105» in an integer variable to use later?
8 Contributors
10 Replies
20K Views
6 Years Discussion Span
Latest Post 9 Years Ago Latest Post by erim.aljerrah
Recommended Answers Collapse Answers
>This is a program convert a string to ASCII. No, it’s a program that prints the integer value of each character in a string instead of the character representation.
>#include You’re about ten years too late with this. The correct C++ header is , and you need to …
>thats just my idea. You’re making assumptions about what the OP wants to do. Personally I think he’s just not communicating well, because concatenating values like that will quickly reach the limit of the integer data types. Since his «word» has an upper limit of 32 characters, overflow or wraparound …
Hi, this is exactly what i’m trying to do. Any ideas would be very helpfull. In effect I want to store the ascii generated numbers in individual locations.
Please refer to the last few pages of the hot thread on computing Sqrt without using Sqrt() and Pwr …
All 10 Replies
>This is a program convert a string to ASCII. No, it’s a program that prints the integer value of each character in a string instead of the character representation. >#include You’re about ten years too late with this. The correct C++ header is , and you need to qualify for the std namespace as well since every name in the standard library is now contained in it. >cin >> word; No, this is very bad. If you must use operator >> to read strings, include and force a maximum field width with setw. >while (word[x] != ‘\0’) A for loop would be better here, or if you still want to use a while loop, declare x closer to it. C++ lets you declare variables anywhere in your function. They don’t have to be at the top of a block. >cout You probably want some whitespace in the output so that you can tell where one character ends and another starts. >cout If you’re only printing one character, there’s no need to use the string «\n». You can use just a single character as well:
>return 0; This isn’t required anymore. 0 is returned automagically when you fall off the end of main (but that rule only applies to main). This is better:
#include #include int main() < char word[32]; std::cout> std::setw ( sizeof word ) >> word; std::cout How do you plan to use it?
tracethepath-2Junior Poster in Training
what i think you can do is save each value of int(word[x]) in an integer array. and then add them like 104*1000+105=sum and then if it is ghi 103*pow(10, 6)+sum=sum. and so on. thats just my idea. there can be a better way.
Narue5,707Bad CopTeam Colleague
>thats just my idea. You're making assumptions about what the OP wants to do. Personally I think he's just not communicating well, because concatenating values like that will quickly reach the limit of the integer data types. Since his "word" has an upper limit of 32 characters, overflow or wraparound is guaranteed for all but the shortest of words.
Baalzamon0Newbie Poster
Hi, this is exactly what i'm trying to do. Any ideas would be very helpfull. In effect I want to store the ascii generated numbers in individual locations.
yonghc29Junior Poster in Training
Hi, this is exactly what i'm trying to do. Any ideas would be very helpfull. In effect I want to store the ascii generated numbers in individual locations.
Dear Baalzamon,
Please refer to the last few pages of the hot thread on computing Sqrt without using Sqrt() and Pwr functions. The codes in my program may help you find an answer. Just store the ASCII value after each character was entered, in an array.
Как можно перевести строку в ASCII коды? Есть ли возможность переводить сразу, а не через char? Спасибо.
Перевести из int в string по таблице ascii подскажите как перевести из числа в символ? есть int a = 97; как получить std::string = "a" ?
Как ковертировать из ASCII опять в string? Всем доброго здравия. Нашел программу, которая переводит буквы строки в порядковые номера по.
Перевод кириллицы в ASCII Задание: В заданной строке после каждой буквы русского алфавита поставить ее код, а после.
Перевод символов в ASCII #include <iostream> #include <string> using namespace std; int main () < int a, b; cin.
Сообщение от rtr
Как можно перевести строку в ASCII коды? Есть ли возможность переводить сразу, а не через char? Спасибо.
никаких усилий не нужно приведу пример:
char c ='e';int n = c;// n = 101 тобиш е имеет аски код 101//-------------------------------------------constint n =10;char m[n];int m2[n];for(int i =0; i n ; i++) m2[i]= m[i];
Сообщение от лендер
никаких усилий не нужно приведу пример:
char c ='e';int n = c;// n = 101 тобиш е имеет аски код 101//-------------------------------------------constint n =10;char m[n];int m2[n];for(int i =0; i n ; i++) m2[i]= m[i];
спс, но это я знаю). у меня вначале string. как его перевести в char? или можно как-то сразу в ascii?
Сообщение от rtr
Сообщение от CyBOSSeR
string s='abcd';int i; i=(int)s.c_str();
std::string str ='abcd';int* ascii_str =newint[str.lenght()];for(int i =0; i str.lenght();++i) ascii_str[i]= str[i];
Сообщение от CyBOSSeR
std::string str ='abcd';int* ascii_str =newint[str.lenght()];for(int i =0; i str.lenght();++i) ascii_str[i]= str[i];
спасибо) но можно как нибудь без массива обойтись? у меня строка из файла считывается и втесать этот код представляется затруднительным
Сообщение от CyBOSSeR
Вообщем. прикрутил, спасибо (только там length должно быть ) теперь правда, ещё один вопрос появился, если в строке перемешаны цифры и буквы (точнее разделены точкой: вася.241), как их отделить?
for(i =0; i str.length(); i++)if(str[i]=='.') str[i]=' ';
Добавлено через 10 минут есть еще вариант, если элемент массива str не равен букве, то мы сдвигаем весь массив на этот символ и запоминаем кол-во таких символов, чтобы перевыделить правильно память или забить конец массива нулями к примеру можно слова переписывать в массив строк, пока не встретится другой символ, а цифры соответственно в обычный массив, или что именно вам нужно?
Сообщение от Vorona
for(i =0; i str.length(); i++)if(str[i]=='.') str[i]=' ';
Добавлено через 10 минут есть еще вариант, если элемент массива str не равен букве, то мы сдвигаем весь массив на этот символ и запоминаем кол-во таких символов, чтобы перевыделить правильно память или забить конец массива нулями к примеру можно слова переписывать в массив строк, пока не встретится другой символ, а цифры соответственно в обычный массив, или что именно вам нужно?
я решил не проверять файл два раза а забацил следующим образом
if(atoi(str.c_str())==0){int* ascii_str1 =newint[str.length()];for(int i =0; i str.length(); i++) ascii_str1[i]= str[i];for(int i =0; i str.length(); i++)cout[i];}else val=atoi(str.c_str());
немного глупо, но вопрос решает. Правда тут у меня ещё одна проблема появилась, после последней буквы слова появляется ascii код 44. Как от него можно избавиться? И как заставить компилятор преобразовать фрагмент 44-44-44 преобразовывать как строку, а не цифру?
Hi, how can I convert a string to ASCII code? I looked up examples in Google but they all use arrays and advance codes, I haven't learned arrays yet, can someone explain me how to convert it please?
Привет всем! Прошу помочь кое что выяснить. Есть ли в С++ функция перевода строки в символы ASCII таблицы? Если все же такой нет, прошу помочь написать её. К примеру такая строка char str[]="4142435a"
Вывести на экран символы строки по возрастанию их кода ASCII 2) После ввода с клавиатуры произвольного ряда, вывести на экран этот ряд с отсортированными в нем.
Перевод десятичных кодов в символы ASCII Вывести на экран заданный интервал(задается двумя числами - границами интервала, нужна проверка.
Из заданной строки исключить все символы, входящие в нее более одного раза (ASCII-Z строки) Здравствуйте! Есть проблемы с выполнением задания: Из заданной строки исключить все символы.
Как удалить ASCII символы из строки Есть строка, из нее нужно удалить ASCII символы, подскажите как это сделать?
Введите цифровую строку, длиной, кратной трём, и будет Вам счастье. Например, Hello! будет иметь такой ASCII-код: 072101108108111033, а Привет! - такой 207240232226229242033 в кодировке Windows 1251.
#include #include usingnamespace std;int main()//читаем по три цифры и выводим символ, соответствующий ASCII-кодуunsignedchar c;for(int i =0; i len; i +=3){ c =(s[i]-48)*100+(s[i+1]-48)*10+ s[i+2]-48;cout;}cout;return0;}