我試圖從用戶輸入中讀取一個字串,然后將其列印在螢屏上。但是,當字串列印在控制臺上時,它是一種胡言亂語。有趣的是,它適用于 Visual Studio 而不是 CodeBlocks。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main() {
int i, num_bytes;
char sentence[] = "";
std::cout << "Please enter your name: ";
//fgets(sentence, 100, stdin);
//scanf("%[^\n]%*c", sentence);
//scanf("%[^\n]", sentence);
std::cin >> sentence;
num_bytes = strlen(sentence);
LPVOID ptr = VirtualAlloc(NULL, num_bytes, MEM_RESERVE, PAGE_READWRITE);
ptr = VirtualAlloc(ptr, num_bytes, MEM_COMMIT, PAGE_READWRITE);
if (ptr) {
char* char_ptr = static_cast<char*>(ptr);
for (i = 0; i < num_bytes; i ) {
char_ptr[i] = sentence[i];
}
std::cout << "Allocated Memory Address: " << (void *)ptr << std::endl;
std::cout << "Press Enter to print out the characters.\n";
getchar();
for (i = 0; i < num_bytes; i ) {
std::cout << char_ptr[i];
}
std::cout << "\nPress Enter to clear memory." << std::endl;
getchar();
VirtualFree(ptr, 0, MEM_RELEASE);
} else {
std::cout << "Could not allocate " << num_bytes << " of memory." << std::endl;
}
std::cout << "\nPress Enter to continue." << std::endl;
getchar();
}
uj5u.com熱心網友回復:
您應該明確指定字串的記憶體大小。那個代碼:
char sentence[] = "";
宣告最大大小的句子為 0( 1 零符號)。當然,您將更多資料寫入非您的記憶體中。試試這個:
char sentence[200] = "";
uj5u.com熱心網友回復:
取而代之的是:
char sentence[] = "";
std::cout << "Please enter your name: ";
//fgets(sentence, 100, stdin);
//scanf("%[^\n]%*c", sentence);
//scanf("%[^\n]", sentence);
std::cin >> sentence;
num_bytes = strlen(sentence);
你最好這樣寫:
constexpr std::streamsize BUFFER_SIZE { 100 };
std::array<char, BUFFER_SIZE> sentence { }; // use the more modern std::array
std::cout << "Please enter your name: ";
std::cin.getline( sentence.data( ), BUFFER_SIZE ); // will only read 100 chars
// including spaces and tabs
num_bytes = strlen(sentence.data( ));
其余的與您的代碼相同。但是現在用戶也可以輸入空格字符并且它們不會導致緩沖區溢位,因為std::cin.getline只會從標準輸入流中讀取有限數量的字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/391483.html
上一篇:Winapi:如何根據按下的鍵為我的按鈕發送不同的訊息?
下一篇:更改uwp行程的標題
