String to ascii cpp

How to convert a string to ASCII ?

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

>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:

Читайте также:  What is public api in java

>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?

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.

>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.

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.

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.

c = getch();

Источник

Перевод из string в ASCII

Как можно перевести строку в 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 //------------------------------------------- const int 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 //------------------------------------------- const int 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 = new int[str.lenght()]; for (int i = 0; i  str.lenght(); ++i) ascii_str[i] = str[i];

ЦитатаСообщение от CyBOSSeR Посмотреть сообщение

std::string str ='abcd'; int* ascii_str = new int[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 = new int[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 преобразовывать как строку, а не цифру?

Источник

String to ascii cpp

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?

I know I can't convert directly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 using namespace std; int main() < string user; getline(cin, user); cout static_castchar>(user); return 0; >

A string obtained via getline is a series of ASCII characters.

Line 11: You can't convert an entire string into a single character.

You can however reference individual characters of the string:

 cout // Assumes the string is not empty 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 using namespace std; int main() < string user; int ascChar; getline(cin, user); cout for (int i=0;i return 0; >

AbstractionAnon when you say [0] what does the brackets mean?

CodeWriter that's the same code I found online, what does these mean?

returns the number of characters in the string list user.
Strings are lists of ascii number codes in the computer.

Источник

Перевод строки в ASCII символы

Привет всем!
Прошу помочь кое что выяснить.
Есть ли в С++ функция перевода строки в символы ASCII таблицы?
Если все же такой нет, прошу помочь написать её.
К примеру такая строка
char str[]="4142435a"

Вывести на экран символы строки по возрастанию их кода ASCII
2) После ввода с клавиатуры произвольного ряда, вывести на экран этот ряд с отсортированными в нем.

Перевод десятичных кодов в символы ASCII
Вывести на экран заданный интервал(задается двумя числами - границами интервала, нужна проверка.

Из заданной строки исключить все символы, входящие в нее более одного раза (ASCII-Z строки)
Здравствуйте! Есть проблемы с выполнением задания: Из заданной строки исключить все символы.

Как удалить ASCII символы из строки
Есть строка, из нее нужно удалить ASCII символы, подскажите как это сделать?

Введите цифровую строку, длиной, кратной трём, и будет Вам счастье.
Например, Hello! будет иметь такой ASCII-код: 072101108108111033, а Привет! - такой 207240232226229242033 в кодировке Windows 1251.

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 29 30 31 32 33 34
#include #include using namespace std; int main()  //читаем по три цифры и выводим символ, соответствующий ASCII-коду unsigned char 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  ; return 0; }

Источник

Оцените статью