Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

getline.ino 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Example of getline from section 27.7.1.3 of the C++ standard
  3. * Demonstrates the behavior of getline for various exceptions.
  4. * See http://www.cplusplus.com/reference/iostream/istream/getline/
  5. *
  6. * Note: This example is meant to demonstrate subtleties the standard and
  7. * may not the best way to read a file.
  8. */
  9. #include <SPI.h>
  10. #include "SdFat.h"
  11. #include "sdios.h"
  12. // SD chip select pin
  13. const uint8_t chipSelect = SS;
  14. // file system object
  15. SdFat sd;
  16. // create a serial stream
  17. ArduinoOutStream cout(Serial);
  18. //------------------------------------------------------------------------------
  19. void makeTestFile() {
  20. ofstream sdout("getline.txt");
  21. // use flash for text to save RAM
  22. sdout << F(
  23. "short line\n"
  24. "\n"
  25. "17 character line\n"
  26. "too long for buffer\n"
  27. "line with no nl");
  28. sdout.close();
  29. }
  30. //------------------------------------------------------------------------------
  31. void testGetline() {
  32. const int line_buffer_size = 18;
  33. char buffer[line_buffer_size];
  34. ifstream sdin("getline.txt");
  35. int line_number = 0;
  36. while (sdin.getline(buffer, line_buffer_size, '\n') || sdin.gcount()) {
  37. int count = sdin.gcount();
  38. if (sdin.fail()) {
  39. cout << "Partial long line";
  40. sdin.clear(sdin.rdstate() & ~ios_base::failbit);
  41. } else if (sdin.eof()) {
  42. cout << "Partial final line"; // sdin.fail() is false
  43. } else {
  44. count--; // Don’t include newline in count
  45. cout << "Line " << ++line_number;
  46. }
  47. cout << " (" << count << " chars): " << buffer << endl;
  48. }
  49. }
  50. //------------------------------------------------------------------------------
  51. void setup(void) {
  52. Serial.begin(9600);
  53. // Wait for USB Serial
  54. while (!Serial) {
  55. SysCall::yield();
  56. }
  57. // F stores strings in flash to save RAM
  58. cout << F("Type any character to start\n");
  59. while (!Serial.available()) {
  60. SysCall::yield();
  61. }
  62. // Initialize at the highest speed supported by the board that is
  63. // not over 50 MHz. Try a lower speed if SPI errors occur.
  64. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
  65. sd.initErrorHalt();
  66. }
  67. // make the test file
  68. makeTestFile();
  69. // run the example
  70. testGetline();
  71. cout << "\nDone!\n";
  72. }
  73. //------------------------------------------------------------------------------
  74. void loop(void) {}