logo

Преобразувайте низ в цяло число в C++

Този раздел ще обсъди различните методи за преобразуване на даден низ данни в цяло число с помощта на езика за програмиране C++. Има някои ситуации или примери, в които трябва да преобразуваме определени данни в друг тип и една такава ситуация е да преобразуваме низ в int данни при програмиране.

Например, имаме числов низ като ' 143 ' и искаме да го преобразуваме в числов тип. Трябва да използваме функция, която преобразува низ в цяло число и връща числовите данни като 143. Сега ще научим всеки метод, който помага за преобразуването на низови данни в цели числа в езика за програмиране C++.

Преобразувайте низ в цяло число в C++

Различни методи за преобразуване на низовите данни в цели числа в езика за програмиране C++.

  1. Използване на класа stringstream
  2. Използване на функцията stoi().
  3. Използване на функцията atoi().
  4. Използване на функцията sscanf().

Използване на класа stringstream

The низов поток е клас, използван за преобразуване на числов низ в тип int. Класът stringstream декларира обект на поток, за да вмъкне низ като обект на поток и след това извлича преобразуваните цели числа на базата на потоците. Класът stringstream има оператори „<>“, които се използват за извличане на данни от левия оператор (<>).

Нека създадем програма, за да демонстрираме класа stringstream за преобразуване на низовите данни в цяло число в езика за програмиране C++.

дата към низ

Program1.cpp

 #include #include // use stringstream class using namespace std; int main() { string str1 = &apos;143&apos;; // declare a string int intdata; // declare integer variable /* use stringstream class to declare a stream object to insert a string and then fetch as integer type data. */ stringstream obj; obj &lt;&gt; intdata; // fetch integer type data cout &lt;&lt; &apos; The string value is: &apos; &lt;&lt; str1 &lt;&lt; endl; cout &lt;&lt; &apos; The representation of the string to integer type data is: &apos; &lt;&lt; intdata &lt;&lt; endl; return 0; } 

Изход

 The string value is: 143 The representation of the string to integer type data is: 143 

В горната програма използваме класа stringstream, за да създадем obj обект и той помага за преобразуването на низови данни в цяло число. След това използваме оператора „<>“, за да извлечем преобразувания низ от obj в числови данни.

Използване на функцията sscanf().

Функция sscanf() преобразува даден низ в определен тип данни като цяло число.

Синтаксис

 sccanf ( str, %d, &amp;intvar); 

Функцията sscanf() има три аргумента за указване на символния низ (str), спецификатора на данни (%d) и целочислената променлива (&intvar) за съхраняване на преобразувания низ.

Алгоритъм на функцията sscanf().

  1. Функцията sscanf() принадлежи към класа stringstream, така че трябва да импортираме класа в нашата програма.
  2. Инициализиране на постоянен символен низ str.
  3. Създайте целочислена променлива, за да задържите преобразувания низ в цели числа.
  4. Предайте низовата променлива във функцията sscanf() и присвоете функцията sscanf() на целочислената променлива, за да съхраните целочислената стойност, генерирана от функцията.
  5. Отпечатайте целочислените стойности.

Нека разгледаме пример за използване на функцията sscanf() за преобразуване на низа в числово число в C++.

Program2.cpp

 #include #include // use stringstream class using namespace std; int main () { // declare the character strings const char *str1 = &apos;555&apos;; const char *str2 = &apos;143&apos;; const char *str3 = &apos;101&apos;; // declare the integer variables int numdata1; int numdata2; int numdata3; /* use sscanf() function and to pass the character string str1, and an integer variable to hold the string. */ sscanf (str1, &apos;%d&apos;, &amp;numdata1); cout &lt;<' the value of character string is: ' << str1; cout '
 representation to int numdata1 <<endl; sscanf (str2, '%d', &numdata2); <<'
 str2; numdata2 (str3, &numdata3); str3; numdata3 return 0; } < pre> <p> <strong>Output</strong> </p> <pre> The value of the character string is: 555 The representation of string to int value of numdata is: 555 The value of the character string is: 143 The representation of string to int value of numdata is: 143 The value of the character string is: 101 The representation of string to int value of numdata is: 101 </pre> <h3>Using the stoi() function</h3> <p>The stoi() function converts a string data to an integer type by passing the string as a parameter to return an integer value.</p> <p> <strong>Syntax</strong> </p> <pre> stoi(str); </pre> <p>The stoi() function contains an str argument. The str string is passed inside the stoi() function to convert string data into an integer value.</p> <p> <strong>Algorithm of the stoi() function</strong> </p> <ol class="points"> <li>Initialize the string variable to store string values.</li> <li>After that, it creates an integer type variable that stores the conversion of string into integer type data using the stoi() function.</li> <li>Print the integer variable value.</li> </ol> <p>Let&apos;s create a program to use the stoi() function to convert the string value into the integer type in the C++ programming language.</p> <p> <strong>Program3.cpp</strong> </p> <pre> #include #include using namespace std; int main () { string strdata1 = &apos;108&apos;; string strdata2 = &apos;56.78&apos;; string strdata3 = &apos;578 Welcome&apos;; // use stoi() function to pass string as arguments int intdata1 = stoi (strdata1); int intdata2 = stoi (strdata2); int intdata3 = stoi (strdata3); // print the converted values cout &lt;&lt; &apos; The conversion of string to an integer using stoi(&apos;&apos; &lt;&lt; strdata1 &lt;&lt; &apos;&apos;) is &apos; &lt;&lt; intdata1 &lt;<endl; cout << ' the conversion of string to an integer using stoi(\'' strdata2 '\') is intdata2 <<endl; strdata3 intdata3 return 0; } < pre> <p> <strong>Output</strong> </p> <pre> The conversion of string to an integer using stoi(&apos;108&apos;) is 108 The conversion of string to an integer using stoi(&apos;56.78&apos;) is 56 The conversion of string to an integer using stoi(&apos;578 Welcome&apos;) is 578 </pre> <h3>Using the atoi() function</h3> <p>An atoi() function is used to convert the character string into an integer value. An atoi() function passes the character type string to return the integer data.</p> <p> <strong>Syntax</strong> </p> <pre> atoi (const char *str); </pre> <p> <strong>Algorithm of the atoi() function</strong> </p> <ol class="points"> <li>Initialize a pointer-type character array to store a string.</li> <li>After that, it creates an integer type variable that stores the conversion of string into integer type data using the atoi() function.</li> <li>Print the integer variable value.</li> </ol> <p>Let&apos;s create a program to use the atoi() function to convert the string value into the integer type in the C++ programming language.</p> <p> <strong>Program4.cpp</strong> </p> <pre> #include #include using namespace std; int main () { // declare a constant character array of string const char *strdata1 = &apos;256&apos;; const char *strdata2 = &apos;16.18&apos;; const char *strdata3 = &apos;1088 Good Bye&apos;; // use atoi() function to pass character type array as arguments int intdata1 = atoi (strdata1); int intdata2 = atoi (strdata2); int intdata3 = atoi (strdata3); // print the converted values cout &lt;&lt; &apos; The conversion of string to an integer value using atoi(&apos;&apos; &lt;&lt; strdata1 &lt;&lt; &apos;&apos;) is &apos; &lt;&lt; intdata1 &lt;<endl; cout << ' the conversion of string to an integer value using atoi(\'' strdata2 '\') is intdata2 <<endl; strdata3 intdata3 return 0; } < pre> <p> <strong>Output</strong> </p> <pre> The conversion of string to an integer value using atoi(&apos;256&apos;) is 256 The conversion of string to an integer value using atoi(&apos;16.18&apos;) is 16 The conversion of string to an integer value using atoi(&apos;1088 Good Bye&apos;) is 1088 </pre> <hr></endl;></pre></endl;></pre></'>

Използване на функцията stoi().

Функцията stoi() преобразува низови данни в целочислен тип, като предава низа като параметър, за да върне целочислена стойност.

java string to int

Синтаксис

 stoi(str); 

Функцията stoi() съдържа str аргумент. Низът str се предава във функцията stoi() за преобразуване на данни от низ в целочислена стойност.

Алгоритъм на функцията stoi().

  1. Инициализирайте низовата променлива, за да съхранявате низови стойности.
  2. След това той създава променлива от тип цяло число, която съхранява преобразуването на низ в данни от тип цяло число, използвайки функцията stoi().
  3. Отпечатайте стойността на целочислената променлива.

Нека създадем програма, която да използва функцията stoi() за преобразуване на низовата стойност в целочислен тип в езика за програмиране C++.

Program3.cpp

балонно сортиране в алгоритъма
 #include #include using namespace std; int main () { string strdata1 = &apos;108&apos;; string strdata2 = &apos;56.78&apos;; string strdata3 = &apos;578 Welcome&apos;; // use stoi() function to pass string as arguments int intdata1 = stoi (strdata1); int intdata2 = stoi (strdata2); int intdata3 = stoi (strdata3); // print the converted values cout &lt;&lt; &apos; The conversion of string to an integer using stoi(&apos;&apos; &lt;&lt; strdata1 &lt;&lt; &apos;&apos;) is &apos; &lt;&lt; intdata1 &lt;<endl; cout << \' the conversion of string to an integer using stoi(\'\' strdata2 \'\') is intdata2 <<endl; strdata3 intdata3 return 0; } < pre> <p> <strong>Output</strong> </p> <pre> The conversion of string to an integer using stoi(&apos;108&apos;) is 108 The conversion of string to an integer using stoi(&apos;56.78&apos;) is 56 The conversion of string to an integer using stoi(&apos;578 Welcome&apos;) is 578 </pre> <h3>Using the atoi() function</h3> <p>An atoi() function is used to convert the character string into an integer value. An atoi() function passes the character type string to return the integer data.</p> <p> <strong>Syntax</strong> </p> <pre> atoi (const char *str); </pre> <p> <strong>Algorithm of the atoi() function</strong> </p> <ol class="points"> <li>Initialize a pointer-type character array to store a string.</li> <li>After that, it creates an integer type variable that stores the conversion of string into integer type data using the atoi() function.</li> <li>Print the integer variable value.</li> </ol> <p>Let&apos;s create a program to use the atoi() function to convert the string value into the integer type in the C++ programming language.</p> <p> <strong>Program4.cpp</strong> </p> <pre> #include #include using namespace std; int main () { // declare a constant character array of string const char *strdata1 = &apos;256&apos;; const char *strdata2 = &apos;16.18&apos;; const char *strdata3 = &apos;1088 Good Bye&apos;; // use atoi() function to pass character type array as arguments int intdata1 = atoi (strdata1); int intdata2 = atoi (strdata2); int intdata3 = atoi (strdata3); // print the converted values cout &lt;&lt; &apos; The conversion of string to an integer value using atoi(&apos;&apos; &lt;&lt; strdata1 &lt;&lt; &apos;&apos;) is &apos; &lt;&lt; intdata1 &lt;<endl; cout << \' the conversion of string to an integer value using atoi(\'\' strdata2 \'\') is intdata2 <<endl; strdata3 intdata3 return 0; } < pre> <p> <strong>Output</strong> </p> <pre> The conversion of string to an integer value using atoi(&apos;256&apos;) is 256 The conversion of string to an integer value using atoi(&apos;16.18&apos;) is 16 The conversion of string to an integer value using atoi(&apos;1088 Good Bye&apos;) is 1088 </pre> <hr></endl;></pre></endl;>

Използване на функцията atoi().

Функцията atoi() се използва за преобразуване на символния низ в цяло число. Функция atoi() предава символния тип низ, за ​​да върне целите данни.

Синтаксис

 atoi (const char *str); 

Алгоритъм на функцията atoi().

  1. Инициализирайте масив от символи от тип указател, за да съхраните низ.
  2. След това той създава променлива от тип цяло число, която съхранява преобразуването на низ в данни от тип цяло число, използвайки функцията atoi().
  3. Отпечатайте стойността на целочислената променлива.

Нека създадем програма, която да използва функцията atoi() за преобразуване на низовата стойност в целочислен тип в езика за програмиране C++.

Program4.cpp

 #include #include using namespace std; int main () { // declare a constant character array of string const char *strdata1 = &apos;256&apos;; const char *strdata2 = &apos;16.18&apos;; const char *strdata3 = &apos;1088 Good Bye&apos;; // use atoi() function to pass character type array as arguments int intdata1 = atoi (strdata1); int intdata2 = atoi (strdata2); int intdata3 = atoi (strdata3); // print the converted values cout &lt;&lt; &apos; The conversion of string to an integer value using atoi(&apos;&apos; &lt;&lt; strdata1 &lt;&lt; &apos;&apos;) is &apos; &lt;&lt; intdata1 &lt;<endl; cout << \' the conversion of string to an integer value using atoi(\'\' strdata2 \'\') is intdata2 <<endl; strdata3 intdata3 return 0; } < pre> <p> <strong>Output</strong> </p> <pre> The conversion of string to an integer value using atoi(&apos;256&apos;) is 256 The conversion of string to an integer value using atoi(&apos;16.18&apos;) is 16 The conversion of string to an integer value using atoi(&apos;1088 Good Bye&apos;) is 1088 </pre> <hr></endl;>