Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน strtol() ใน C++


ฟังก์ชัน strol() ใช้เพื่อแปลงสตริงเป็นจำนวนเต็มแบบยาว มันตั้งค่าตัวชี้ให้ชี้ไปที่อักขระตัวแรกหลังจากตัวสุดท้าย ไวยากรณ์เป็นเหมือนด้านล่าง ฟังก์ชันนี้มีอยู่ในไลบรารี cstdlib

long int strtol(const char* str, char ** end, int base)

ฟังก์ชันนี้รับสามอาร์กิวเมนต์ อาร์กิวเมนต์เหล่านี้เป็นเหมือนด้านล่าง −

  • str: นี่คือจุดเริ่มต้นของสตริง
  • str_end: ฟังก์ชัน str_end ถูกกำหนดโดยฟังก์ชันเป็นอักขระตัวถัดไป ต่อจากอักขระที่ถูกต้องตัวสุดท้าย หากมีอักขระใดๆ มิฉะนั้นจะเป็นค่าว่าง
  • ฐาน: สิ่งนี้ระบุฐาน ค่าฐานสามารถเป็น (0, 2, 3, …, 35, 36)

ฟังก์ชันนี้จะคืนค่า int แบบยาวที่แปลงแล้ว เมื่ออักขระชี้ไปที่ NULL จะคืนค่า 0

ตัวอย่าง

#include <iostream>
#include<cstdlib>
using namespace std;
main() {
   //Define two string
   char string1[] = "777HelloWorld";
   char string2[] = "565Hello";
   char* End; //The end pointer
   int base = 10;
   int value;
   value = strtol(string1, &End, base);
   cout << "The string Value = " << string1 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End << "\n"; //remaining string after long long integer
   value = strtol(string2, &End, base);
   cout << "\nThe string Value = " << string2 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End; //remaining string after long long integer
}

ผลลัพธ์

The string Value = 777HelloWorld
Long Long Int value = 777
End String = HelloWorld
The string Value = 565Hello
Long Long Int value = 565
End String = Hello

ทีนี้มาดูตัวอย่างด้วยค่าฐานที่ต่างกัน ฐานคือ 16 โดยการนำสตริงของฐานที่กำหนดมา จะพิมพ์ในรูปแบบทศนิยม

ตัวอย่าง

#include <iostream>
#include<cstdlib>
using namespace std;
main() {
   //Define two string
   char string1[] = "5EHelloWorld";
   char string2[] = "125Hello";
   char* End; //The end pointer
   int base = 16;
   int value;
   value = strtol(string1, &End, base);
   cout << "The string Value = " << string1 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End << "\n"; //remaining string after long long integer
   value = strtol(string2, &End, base);
   cout << "\nThe string Value = " << string2 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End; //remaining string after long long integer
}

ผลลัพธ์

The string Value = 5EHelloWorld
Long Long Int value = 94
End String = HelloWorld
The string Value = 125Hello
Long Long Int value = 293
End String = Hello

ในที่นี้สตริงประกอบด้วย 5E ดังนั้นค่าของมันคือ 94 ในหน่วยทศนิยม และสตริงที่สองมี 125 ซึ่งเป็น 293 ในหน่วยทศนิยม